How to use else inside Python's timeit

535 views Asked by At

I am new to using the timeit module, and I'm having a hard time getting multi-line code snippets to run inside timeit.

What works:

timeit.timeit(stmt = "if True: print('hi');")

What does not work (these all fail to even run):

timeit.timeit(stmt = "if True: print('hi'); else: print('bye')")
timeit.timeit(stmt = "if True: print('hi') else: print('bye')")
timeit.timeit(stmt = "if True: print('hi');; else: print('bye')")

I have found that I can use triple-quotes to encapsulate multi-line code segments, but I'd rather just type on one line.

Is there any way to use an else statement inside one line in timeit?

4

There are 4 answers

0
Uriel On BEST ANSWER

The string you provide is interpreted as a source code, so you can use multiline strings with three quotation marks, like

>>> timeit.timeit(stmt = """if True: 'hi'
... else: 'bye'""")
0.015218939913108187

or \n for newlines (but it looks pretty messy)

>>> timeit.timeit(stmt = "if True: 'hi'\nelse: 'bye'")
0.015617805548572505

You can also use ternary if-else condition if you need only a single branch (so no newline is required):

>>> timeit.timeit(stmt = "'hi' if True else 'bye'")
0.030958037935647553
0
Filip Malczak On

Remember about conditional expression: <true val> if <condition> else <false val>

When used with timeit it may look as

timeit.timeit("print('true') if 2+2 == 4 else print('false')")

Notes:

  • this example will work in python3, I wanted to use print as a function, because it was easiest. Of course you can from __future__ import print_function in p2.x
  • this example will obviously output a s*itload od "true"s, be careful while running it
0
Pro Q On

My answer was found within an answer for this question.

You need to have a new line in between the if and else, so it works to do

timeit.timeit(stmt = "if True: print('hi');\nelse: print('bye')")

0
Sergey Byatov On

This code will work the way you want:

timeit.timeit("""
if True: print('hi')
else: print('bye')
""")

Necessarily the presence of a new line