Two of these statements run while the other fails with a syntax error. What am I doing wrong?
>>> Timer('for i in xrange(10): oct(i)').repeat(3)
[2.7091379165649414, 2.6934919357299805, 2.689150094985962]
>>> Timer('n = [] ; n = [oct(i) for i in xrange(10)]').repeat(3)
[4.0500171184539795, 3.6979520320892334, 3.701982021331787]
>>> Timer('n = [] ; for i in xrange(10): n.append(oct(i))').repeat(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/timeit.py", line 136, in __init__
code = compile(src, dummy_src_name, "exec")
File "<timeit-src>", line 6
n = [] ; for i in xrange(10): n.append(oct(i))
^
SyntaxError: invalid syntax
Your failing statement is syntactically incorrect. If you need to time multiple statement’s define it in a function and call Timer, after importing the function from main
Now you need to understand why the failing statement is incorrect
Excerpt from the docs for Compound Statement
A suite can be one or more semicolon-separated simple statements on the same line as the header, following the header’s colon, or it can be one or more indented statements on subsequent lines.
and similarly, a simple statement is
It should now be clear to you when a semi-colon can (not should) be used.