Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using semicolons inside timeit

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.

like image 731
max Avatar asked Apr 24 '12 16:04

max


People also ask

What does %% Timeit do in Python?

%%timeit. You can use the magic command %%timeit to measure the execution time of the cell. As an example, try executing the same process using NumPy . As with %timeit , -n and -r are optional.

How do you use %% Timeit in Jupyter?

The “%timeit” is a line magic command in which the code consists of a single line or should be written in the same line for measuring the execution time. In the “%timeit” command, the particular code is specified after the “%timeit” is separated by a space.

How do you use multiple lines on a Timeit?

The easiest way to time multiple lines having the same indentation is to use semicolons to separate the lines.


1 Answers

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.

like image 123
Andrew Clark Avatar answered Oct 07 '22 06:10

Andrew Clark