>>> import timeit >>> timeit.timeit('"-".join(str(n) for n in range(100))', number=10000) 0.8187260627746582 >>> timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000) 0.7288308143615723 >>> timeit.timeit('"-".join(map(str, range(100)))', number=10000) 0.5858950614929199
其中,number参数是该测试语句重复执行的次数。
示例2
下列代码示例了利用 timeit 同时对3个函数进行计时:
1 2 3 4 5 6 7 8 9
import timeit if __name__ == "__main__" repeats = 1000 for function in ("function_a", "function_b", "function_c"): t = timeit.Timeer("{}(X, Y)".format(function), "from __main__ import {0}, X, Y".format(function)) sec = t.timeit(repeats) / repeats print("{function}() {sec:.6f} sec.format(**locals()))" )
示例3:直接在命令行对代码进行即时
1 2 3 4 5 6
$ python -m timeit '"-".join(str(n) for n in range(100))' 10000 loops, best of 3: 40.3 usec per loop $ python -m timeit '"-".join([str(n) for n in range(100)])' 10000 loops, best of 3: 33.4 usec per loop $ python -m timeit '"-".join(map(str, range(100)))' 10000 loops, best of 3: 25.2 usec per loop
import cProfile if __name__ = "__main__" for function in ("function_a", "function_b", "function_c"): cProfile.run("for i in range(1000):{0}(X, Y)" .format(function))