首页 > 解决方案 > 直接导入子模块有什么好处(似乎更慢)?

问题描述

我想看看哪个更快:

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呢?我这样做是否有记忆好处或其他一些原因?

标签: pythonpython-3.xbenchmarking

解决方案


我尝试使用timebash 命令计时。导入 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.


推荐阅读