python - 直接导入子模块有什么好处(似乎更慢)?
问题描述
我想看看哪个更快:
import numpy as np
np.sqrt(4)
-或者-
from numpy import sqrt
sqrt(4)
这是我用来查找平均运行时间的代码。
def main():
import gen_funs as gf
from time import perf_counter_ns
t = 0
N = 40
for j in range(N):
tic = perf_counter_ns()
for i in range(100000):
imp2() # I ran the code with this then with imp1()
toc = perf_counter_ns()
t += (toc - tic)
t /= N
time = gf.ns2hms(t) # Converts ns to readable object
print("Ave. time to run: {:d}h {:d}m {:d}s {:d}ms" .
format(time.hours, time.minutes, time.seconds, time.milliseconds))
def imp1():
import numpy as np
np.sqrt(4)
return
def imp2():
from numpy import sqrt
sqrt(4)
return
if __name__ == "__main__":
main()
然后当我import numpy as np
调用时,我得到大约229 毫秒np.sqrt(4)
的平均时间(运行循环 10**4 次的时间)。
当我运行from numpy import sqrt
然后调用时,我得到大约332 毫秒sqrt(4)
的平均时间。
既然跑的时间有这么大的差别,那跑有什么好处from numpy import sqrt
呢?我这样做是否有记忆好处或其他一些原因?
解决方案
我尝试使用time
bash 命令计时。导入 numpy 并运行sqrt(4)
需要 215 毫秒,使用相同命令从 numpy 导入 sqrt 需要 193 毫秒。老实说,差异可以忽略不计。
但是,如果您不需要模块的某个方面,则不鼓励导入它。
在这种特殊情况下,由于没有明显的性能优势,并且因为在很少情况下您只导入numpy.sqrt
(math.sqrt
速度快 4 倍。numpy.sqrt
提供的额外功能只有在您有数据时才可用numpy
,这需要您导入当然,整个模块)。
可能有一种罕见的情况,您不需要 allnumpy
但仍然需要numpy.sqrt
,例如pandas.DataFrame.to_numpy()
以某种方式使用和操作数据,但老实说,我觉得 20 毫秒的速度在现实世界中并不值得。特别是因为您看到仅导入numpy.sqrt
.
推荐阅读
- swift - 在 View Swift 5 中附加一个值
- python - 如何让我的不和谐机器人响应 *both* 自定义前缀和提及?
- mysql - 如何减少这个mysql查询执行时间
- sitecore - 安装 Sitecore 9.3 和我的程序集后“对象引用未设置为对象的实例”
- python - 只要按下激活playsound的键,如何让winsound播放声音?
- excel - 为什么激活特定工作表会影响我的宏的运行时间
- callback - 使用 LDAP 的 Keycloak 身份验证不起作用
- flutter - 如何在颤动中从导航器堆栈中弹出最后三个路由
- node.js - 我将如何单独运行相同的应用程序
- antd - 角度蚂蚁设计系统中的 CSS 网格类