时间倍数 python3 脚本

Time multiple python3 scripts

以后我会在Python 3 中写多个我想要计时的小脚本。一种方法是像这样编写每个脚本:

# functions definitions go here

if __name__ == '__main__':
  import time
  start = time.time()

  # my code

  end = time.time()
  print("This script took {} seconds to execute".format(end - start))

但我必须将其写入这些脚本中的每一个。在不每次都包含此代码的情况下为我的脚本计时的最佳方法是什么(不会丢失准确性 - 我知道 time ./script.py)?

使用timeit vs 时间模块。这最适合比较一种做某事的方式与另一种做同一件事的方式。

这是一个非常简单的模板:

# if f1,f2,f3 are in another module or script, just import...
def f1(s):
    # that function returns something...

def f2(s):
    # etc

def f3(s):
    # etc 

if __name__=='__main__':
    import timeit    
    for case, x in (('small',1000),('med',10000),('large',1000000)):  
        data=[some data scaled by x]
        print("Case {}, {:,} x, All equal: {}".format(case,x,(f1(data)==f2(data)==f3(data))))
        for f in (f1,f2,f3):
            print("   {:^10s}{:.4f} secs".format(f.__name__, timeit.timeit("f(data)", setup="from __main__ import f, data", number=10)))

这应该可以帮助您入门。请更具体地说明您遇到的问题以获得更具体的答案。

我的一个 other answers 有一个更具竞争力的 timeit 示例。

您还可以查看 cProfile 来分析完整的脚本并确定瓶颈函数。然后使用 timeit 尝试该瓶颈函数的变体。

如果你在类似 unix 的环境中,你可以使用 shell.

如果您与脚本位于同一文件夹中:

$ time python mymodule.py
real    0m0.307s
user    0m0.030s
sys     0m0.030s

如果您在已安装的软件包中安装了脚本(我推荐 ),您可以 运行 从任何地方使用模块名称

$ time python -m mypackage.mymodule
real    0m0.407s
user    0m0.033s
sys     0m0.032s