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.
You need to provide properly indented code with newlines, not semi-colons. Try changing it to the following:
Although this may be more readable as:
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.