我想以forcing division to be floating point的不同方式比较执行时间。
在终端中使用timeit
测试以下代码时,
from __future__ import division
a = 2/3
我遇到错误,
$ python -m timeit '2*1.0/3' # this works
10000000 loops, best of 3: 0.0578 usec per loop
$ python -m timeit -s 'from __future__ import division' '2/3'
Traceback (most recent call last):
File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main
"__main__", fname, loader, pkg_name)
File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals
File "/usr/lib/python2.7/timeit.py", line 330, in <module>
sys.exit(main())
File "/usr/lib/python2.7/timeit.py", line 294, in main
t = Timer(stmt, setup, timer)
File "/usr/lib/python2.7/timeit.py", line 136, in __init__
code = compile(src, dummy_src_name, "exec")
File "<timeit-src>", line 3
SyntaxError: from __future__ imports must occur at the beginning of the file
如何衡量此类代码段的执行时间?
答案 0 :(得分:1)
通过全局启用行为:
$ python -Q new -m timeit '2/3'
10000000 loops, best of 3: 0.0242 usec per loop