python import numpy_独家 | 带你入门比Python更高效的Numpy(附代码)

import numpy as np

from math import sin as sn

import matplotlib.pyplot as plt

import time

# 测试数量

N_point = 1000

# 定义一个有if else循环的函数

def myfunc(x,y):

if (x>0.5*y and y<0.3): return (sn(x-y))

elif (x<0.5*y): return 0

elif (x>0.2*y): return (2*sn(x+2*y))

else: return (sn(y+x))

# 从正态分布产生存储元素的列表

lst_x = np.random.randn(N_point)

lst_y = np.random.randn(N_point)

lst_result = []

# 可选择画出数据分布

plt.hist(lst_x,bins=20)

plt.show()

plt.hist(lst_y,bins=20)

plt.show()

# 首先,纯粹的Python代码

t1=time.time()

First, plain vanilla for-loop

t1=time.time()

for i in range(len(lst_x)):

x = lst_x[i]

y= lst_y[i]

if (x>0.5*y and y<0.3):

lst_result.append(sn(x-y))

elif (x<0.5*y):

lst_result.append(0)

elif (x>0.2*y):

lst_result.append(2*sn(x+2*y))

else:

lst_result.append(sn(y+x))

t2=time.time()

print("nTime taken by the plain vanilla for-loopn----------------------------------------------n{} us".format(1000000*(t2-t1)))

# List comprehension

print("nTime taken by list comprehension and zipn"+'-'*40)

%timeit lst_result = [myfunc(x,y) for x,y in zip(lst_x,lst_y)]

# Map() 函数

print("nTime taken by map functionn"+'-'*40)

%timeit list(map(myfunc,lst_x,lst_y))

# Numpy.vectorize 方法

print("nTime taken by numpy.vectorize methodn"+'-'*40)

vectfunc = np.vectorize(myfunc,otypes=[np.float],cache=False)

%timeit list(vectfunc(lst_x,lst_y))

# 结果

Time taken by the plain vanilla for-loop

----------------------------------------------

2000.0934600830078 us

Time taken by list comprehension and zip

----------------------------------------

1000 loops, best of 3: 810 µs per loop

Time taken by map function

----------------------------------------

1000 loops, best of 3: 726 µs per loop

Time taken by numpy.vectorize method

----------------------------------------

8ecb9063c3ad42719ce8ff4406399cb1.jpeg

1000 loops, best of 3: 516 µs per

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值