ufunc是一种可以对数组每个元素进行运算的函数。Numpy的许多ufunc函数都是用C语言实现的,因此他们的运算速度非常快。
我们举个例子来看一下是怎样运用ufunc函数进行计算的吧!~
同时见识一下ufunc的速度!
import numpy as np
import time
start_time = time.time()
# 你的代码在这里
x = np.linspace(0, 1000*np.pi, 5000)
y =np.sin(x)
print(y)
end_time = time.time()
print(f"代码执行时间: {end_time - start_time} 秒")
由于在 PyCharm 中直接查看 Python 代码的运行速度并不像一些专门的性能分析工具那样直观。但是,我们可以通过time模块来测量代码段的运行时间。
这段代码的运行结果是:
那我们通过其他方式来计算这组数据,并展示运行时间,代码如下:
import time
import math
start_time = time.time()
# 使用四舍五入来计算近似的步长,并生成 x 列表
step = round((1000 * math.pi) / 5000)
x = [i * step for i in range(5001)] # 生成从 0 到 1000*pi 的点,包括两端点
y = [math.sin(val) for val in x] # 使用循环计算每个点的正弦值
print(y) # 打印结果
end_time = time.time()
print(f"代码执行时间: {end_time - start_time} 秒")
运行结果:
可以明显地看出来这种做法,运行时间要慢了许多!