Using semicolons inside timeit

戏子无情 提交于 2019-12-23 07:38:14

问题


I can't seem to get timeit.timeit to work when I have exceptions in the statement argument passed as string:

# after the first and third semicolon, I put 4 spaces 
timeit.timeit('try:;    a=1;except:;    pass')

This results in:

Traceback (most recent call last):
  File "a.py", line 48, in <module>
    timeit.timeit('try:;    a=1;except:;    pass')
  File "C:\CPython33\lib\timeit.py", line 230, in timeit
    return Timer(stmt, setup, timer).timeit(number)
  File "C:\CPython33\lib\timeit.py", line 136, in __init__
    code = compile(src, dummy_src_name, "exec")
  File "<timeit-src>", line 6
    try:;    a=1;except:;    pass
        ^
SyntaxError: invalid syntax

I'm running it with Python 3.3, but the same mistake happens even with the old Python (3.2).

UPDATE:

I was following this documentation (emphasis mine):

class timeit.Timer(stmt='pass', setup='pass', timer=)

Class for timing execution speed of small code snippets.

The constructor takes a statement to be timed, an additional statement used for setup, and a timer function. Both statements default to 'pass'; the timer function is platform-dependent (see the module doc string). stmt and setup may also contain multiple statements separated by ; or newlines, as long as they don’t contain multi-line string literals.


回答1:


You need to provide properly indented code with newlines, not semi-colons. Try changing it to the following:

timeit.timeit('try:\n    a=1\nexcept:\n    pass')

Although this may be more readable as:

stmt = '''\
try:
    a=1
except:
    pass'''
timeit.timeit(stmt)

Semicolons will work fine for separating statements that would have the same indentation level, but any spaces or tabs you put between the semicolon and the next statement will be ignored so you cannot use them with indentation.




回答2:


This is an old thread but it might be worth an update. Another option that uses textwrap to improve readability by allowing code a base level of indentation:

import timeit
import textwrap
print(timeit.timeit(textwrap.dedent("""
  try:
    a=1
  except:
    pass
  """), number=10))


来源:https://stackoverflow.com/questions/10301896/using-semicolons-inside-timeit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!