python -m timeit:SyntaxError:from __future__ imports必须出现在文件的开头

时间:2016-05-14 02:47:48

标签: python python-2.7 timeit

我想以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

如何衡量此类代码段的执行时间?

1 个答案:

答案 0 :(得分:1)

通过全局启用行为:

$ python -Q new -m timeit '2/3'
10000000 loops, best of 3: 0.0242 usec per loop