gpt4 book ai didi

python - Python导入模块的优化

转载 作者:太空狗 更新时间:2023-10-30 01:49:32 25 4
gpt4 key购买 nike

我正在阅读 David Beazley 的 Python 引用书,他提出了一个观点:

For example, if you were performing a lot of square root operations, it is faster to use 'from math import sqrt' and 'sqrt(x)' rather than typing 'math.sqrt(x)'.

和:

For calculations involving heavy use of methods or module lookups, it is almost always better to eliminate the attribute lookup by putting the operation you want to perform into a local variable first.

我决定试一试:

首先()

def first():
from collections import defaultdict
x = defaultdict(list)

第二个()

def second():
import collections
x = collections.defaultdict(list)

结果是:

2.15461492538
1.39850616455

诸如此类的优化对我来说可能无关紧要。但我很好奇为什么与 Beazley 所写的相反。请注意,有 1 秒的差异,鉴于任务微不足道,这很重要。

为什么会这样?

更新:

我得到的时间如下:

print timeit('first()', 'from __main__ import first');
print timeit('second()', 'from __main__ import second');

最佳答案

from collections import defaultdictimport collections 应该在迭代计时循环之外,因为您不会重复执行它们。

我想 from 语法必须比 import 语法做更多的工作。

使用这个测试代码:

#!/usr/bin/env python

import timeit

from collections import defaultdict
import collections

def first():
from collections import defaultdict
x = defaultdict(list)

def firstwithout():
x = defaultdict(list)

def second():
import collections
x = collections.defaultdict(list)

def secondwithout():
x = collections.defaultdict(list)

print "first with import",timeit.timeit('first()', 'from __main__ import first');
print "second with import",timeit.timeit('second()', 'from __main__ import second');

print "first without import",timeit.timeit('firstwithout()', 'from __main__ import firstwithout');
print "second without import",timeit.timeit('secondwithout()', 'from __main__ import secondwithout');

我得到结果:

first with import 1.61359190941
second with import 1.02904295921
first without import 0.344709157944
second without import 0.449721097946

这显示了重复导入的成本。

关于python - Python导入模块的优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5926114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com