python - 从解释器和命令行使用 timeit 的时间差异

标签 python performance timeit

从解释器,我得到:

>>> timeit.repeat("-".join( str(n) for n in range(10000) ) , repeat = 3, number=10000)
[1.2294530868530273, 1.2298660278320312, 1.2300069332122803] # this is seconds 

从命令行,我得到:

$ python -m timeit -n 10000 '"-".join(str(n) for n in range(10000))'
10000 loops, best of 3: 1.79 msec per loop # this is milli second 

为什么这两种情况下的时间差异如此之大?

最佳答案

这两条线测量的不是同一件事。在第一个片段中,您对计算 0-1-2-...-9999 进行了计时。而在第二个片段中,您正在为字符串连接计时 "-".join(str(n) for n in range(10000)).

此外,timeitrepeat 报告 时间,而 CLI 计算迭代次数的平均时间。所以第一个代码实际上“每个循环”需要 12.29 毫秒。

关于python - 从解释器和命令行使用 timeit 的时间差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19413371/

相关文章:

c# - 与命名管道和远程处理相比,WCF 是否存在性能问题?

python - 为什么从生成器对象创建列表需要这么长时间?

Python - 及时克服导入

python - 在 Python 3 中获取所有父类(super class)

python - 使用 Factoradic 系统允许重复时查找第 K 个字典排列

performance - Go:基于类的方法是否比功能更高效?

python - 获取执行耗时

python - 计算字符串中最小长度的唯一单词

Python - 通过索引矩阵构造矩阵

sql-server - SQL Server : Query fast, 但过程缓慢