直接导入子模块有什么好处(似乎比较慢)?

时间:2019-06-28 15:47:19

标签: python python-3.x benchmarking

我想看看哪个更快:

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然后呼叫np.sqrt(4)时,我得到的平均时间约为 229ms (运行循环的时间为10 ** 4次)。

当我运行from numpy import sqrt然后打电话给sqrt(4)时,平均时间约为 332ms

由于运行时间存在这种差异,因此运行from numpy import sqrt有什么好处?我有这样做的记忆优势还是其他原因?

1 个答案:

答案 0 :(得分:0)

我尝试使用start_over = 10 STONKS = raw_input("YESN'T? ") if STONKS == "What?": start_over -= 1 print STONKS elif STONKS == "Yeah?": print "Nah, don't be a bully Ninja" start_over -=1 print STONKS else: print "YOU ATE MY BEANS?!" bash命令计时。使用相同的命令,我有215毫秒用于导入numpy并运行time,还有193毫秒用于从numpy导入sqrt。老实说,差别可以忽略不计。

但是,如果不需要模块的某个方面,则不建议导入。

在这种特殊情况下,由于没有明显的性能优势,并且在极少数情况下仅导入sqrt(4)numpy.sqrt快4倍。额外的功能{{1} }优惠只有在您拥有math.sqrt数据的情况下才可用,这当然需要您导入整个模块。

在少数情况下,您可能不需要numpy.sqrt,但仍然需要numpy,例如使用numpy并以某种方式处理数据,但老实说,我认为20ms的速度在现实世界中不值得。尤其是因为您看到{em {em}} 仅导入numpy.sqrt的性能。