【问题标题】:Why python timeit result is in contradiction with shell's time command?为什么 python timeit 结果与 shell 的 time 命令相矛盾?
【发布时间】:2019-08-08 21:10:21
【问题描述】:

我不太确定我在这里缺少什么,但看起来 shell 中的 time 报告的命令值较高,而 python 中的 timeit 报告的值较低。实际上看起来time 数字是正确的。发生了什么?

time python -m timeit 'd={"i": 1}; d.update({"i": 2, "j": 3, "k": 4})'

导致:

1000000 loops, best of 3: 0.373 usec per loop (timeit)           
1.54s user 0.00s system 99% cpu 1.545 total (time)

time python -m timeit 'd={"i": 1}; d = dict(d, **{"i": 2, "j": 3, "k": 4})'

导致:

1000000 loops, best of 3: 0.43 usec per loop (timeit)            
1.77s user 0.00s system 99% cpu 1.778 total (time)

time python -m timeit 'd={"i": 1}; d["i"] = 2; d["j"] = 3; d["k"] = 4'

导致:

10000000 loops, best of 3: 0.145 usec per loop (timeit)
5.98s user 0.00s system 99% cpu 5.986 total (time)                                                                                                                                                                                    

【问题讨论】:

  • 糟糕!我错过了第三个实际上跑了 10 倍以上......

标签: python time timeit


【解决方案1】:
  • time 告诉您运行基准测试需要多长时间
  • timeit 告诉您运行基准测试所构建的代码需要多长时间

这是两个非常不同的东西。 time 包括启动解释器的所有开销;收集有关您的个人基准测试运行需要多长时间的统计数据;解释这些结果;做任何额外的运行,因为它们不稳定或统计上不合适而被淘汰;在定时调用之间执行垃圾收集;等等

【讨论】:

    【解决方案2】:

    看起来结果并不矛盾,因为第 3 种情况运行了 10 倍以上,达到 10,000,000 次,而情况 1 和 2 运行了 1,000,000 次。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 2016-10-06
      • 2015-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-05
      相关资源
      最近更新 更多