2016-05-14 63 views
1

我想用不同的方式比较forcing division to be floating point的执行时间。python -m timeit:SyntaxError:from __future__进口必须发生在文件的开头

虽然测试与终端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

通过使行为全局:

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

在这种情况下,'2/3'等于'0.66'或'0'? – SparkAndShine

+0

@sparkandshine:你看过手册页来看看'-Q'的功能吗? –

+0

现在,我明白了。 Thx为您的提醒。 – SparkAndShine