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.
timeit.timeit('a=1;b=1')
works fine... – Staten