Using semicolons inside timeit
Asked Answered
S

2

12

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.

Staten answered 24/4, 2012 at 16:19 Comment(0)
A
25

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.

Assentor answered 24/4, 2012 at 16:22 Comment(3)
Thank you.. can you please check the updated question? And in fact timeit.timeit('a=1;b=1') works fine...Staten
@Staten - 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.Assentor
@max, The ; won't work for try/except, for loops, while loops, if blocks, etc. It only works for separating simple statements.Physical
E
0

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))
Eddington answered 23/10, 2017 at 22:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.