每个人!我正在尝试使用对象测试字典的创建性能,但我得到了一些奇怪的结果。我使用了三种不同的方法来测量在 Python 中创建大量字典的时间。第一个解决方案是时间模块。我知道这不准确。测试文件是“node_time.py”
from __future__ import print_function
from time import time
class node(object):
def __init__(self, key, value):
self.key = key
self.value = value
self.right = None
self.left = None
self.parent = None
self.depth = 0
return
begin = time()
content = [node(i,i) for i in range(1000000)]
print(time()-begin)
第二种方法是timeit模块。这应该是一个更好的选择。测试文件是“node_timeit.py”
from __future__ import print_function
from timeit import repeat
class node(object):
def __init__(self, key, value):
self.key = key
self.value = value
self.right = None
self.left = None
self.parent = None
self.depth = 0
return
cmd = "content = [node(i,i) for i in range(1000000)]"
prepare = "from __main__ import node"
cost = min(repeat(cmd, prepare, repeat=1, number =1))
print(cost)
第三种方法是在Linux中使用系统命令“时间”。测试文件是“node_sys.py”
from __future__ import print_function
class node(object):
def __init__(self, key, value):
self.key = key
self.value = value
self.right = None
self.left = None
self.parent = None
self.depth = 0
return
content = [node(i,i) for i in range(1000000)]
最后结果完全不同。
-bash-4.2$ python2 node_time.py
5.93654894829
-bash-4.2$ python2 node_timeit.py
2.6723048687
-bash-4.2$ time python2 node_sys.py
real 0m8.587s
user 0m7.344s
sys 0m0.716s
时间模块法(测量挂钟时间)的结果应该大于当前值。但是使用 Linux 命令“time”,用户 CPU 时间和 sys CPU 时间的总和将高达 8.060 秒。哪个结果是正确的?为什么它们如此不同?感谢您的任何评论!