直接导入子模块有什么好处(似乎更慢)?
Any benefits to importing sub modules directly (seems to be slower)?
我想看看哪个更快:
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)
时,我得到的平均时间约为 229 毫秒 (到 运行 循环 10* 的时间*4 次)。
当我 运行 from numpy import sqrt
然后调用 sqrt(4)
时,我得到的平均时间约为 332ms.
既然到运行有这么大的时间差,对运行宁from numpy import sqrt
有什么好处?有没有我会这样做的记忆好处或其他原因?
我尝试使用 time
bash 命令计时。我得到了 215ms 用于导入 numpy 和 运行 sqrt(4)
和 193ms 用于使用相同的命令从 numpy 导入 sqrt。老实说,差异可以忽略不计。
但是,如果您不需要模块的某个方面,则不鼓励导入它。
在这种特殊情况下,因为没有明显的性能优势,而且在很少情况下您只需要导入 numpy.sqrt
(math.sqrt
快约 4 倍。额外的功能 numpy.sqrt
优惠只有在您有 numpy
数据时才可用,当然,这需要您导入整个模块。
在这种情况下,您可能不需要全部 numpy
但仍然需要 numpy.sqrt
,例如使用 pandas.DataFrame.to_numpy()
并以某种方式操纵数据,但老实说,我不觉得 20 毫秒的速度在现实世界中有任何价值。特别是因为您看到仅导入 numpy.sqrt
.
的 更差 性能
我想看看哪个更快:
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)
时,我得到的平均时间约为 229 毫秒 (到 运行 循环 10* 的时间*4 次)。
当我 运行 from numpy import sqrt
然后调用 sqrt(4)
时,我得到的平均时间约为 332ms.
既然到运行有这么大的时间差,对运行宁from numpy import sqrt
有什么好处?有没有我会这样做的记忆好处或其他原因?
我尝试使用 time
bash 命令计时。我得到了 215ms 用于导入 numpy 和 运行 sqrt(4)
和 193ms 用于使用相同的命令从 numpy 导入 sqrt。老实说,差异可以忽略不计。
但是,如果您不需要模块的某个方面,则不鼓励导入它。
在这种特殊情况下,因为没有明显的性能优势,而且在很少情况下您只需要导入 numpy.sqrt
(math.sqrt
快约 4 倍。额外的功能 numpy.sqrt
优惠只有在您有 numpy
数据时才可用,当然,这需要您导入整个模块。
在这种情况下,您可能不需要全部 numpy
但仍然需要 numpy.sqrt
,例如使用 pandas.DataFrame.to_numpy()
并以某种方式操纵数据,但老实说,我不觉得 20 毫秒的速度在现实世界中有任何价值。特别是因为您看到仅导入 numpy.sqrt
.