当前位置:网站首页>On the operation mechanism of numpy array

On the operation mechanism of numpy array

2022-06-27 01:40:00 Colonization armor Kemp

List of articles

Preface

numpy The array can be directly operated with a scalar to realize the operation by elements , Very concise , But if this scalar is also a function , How to write more efficiently ? Such as normalization , Array / Array and , It's direct /np.sum( Array ) Or do you get the array first and then do the operation ?

experiment

The way a Namely /np.sum( Array ), The way b Is to get the array first and then operate , Because the array size is limited , Here, several iterations have been carried out to widen the gap :

import numpy as np
import time


def timer(start, name):
    duration = time.time() - start
    time_list = [0, 0, 0]
    time_list[0] = duration // 3600
    time_list[1] = (duration % 3600) // 60
    time_list[2] = round(duration % 60, 2)
    print(name + ' when :' + str(time_list[0]) + '  when  ' + str(time_list[1]) + ' branch ' + str(time_list[2]) + ' second ')


def a(nums):
    nums = nums / np.sum(nums)


def b(nums):
    sum_ = np.sum(nums)
    nums = nums / sum_


x = np.random.randn(500000000)
iter = 100

s = time.time()
for _ in range(iter):
    a(x)
timer(s, 'a')

s = time.time()
for _ in range(iter):
    b(x)
timer(s, 'b')

Output :

a when :0.0  when  3.0 branch 34.98 second 
b when :0.0  when  3.0 branch 11.88 second 

It can be seen that it is faster to sum first and then calculate .

Because I didn't find it numpy Implementation mechanism , So observe through experiments , If you have any friends who understand the mechanism, please don't hesitate to comment .

原网站

版权声明
本文为[Colonization armor Kemp]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/178/202206270125448991.html