How to use else inside Python's timeit
Asked Answered
P

4

6

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?

Parameter answered 9/1, 2017 at 18:13 Comment(0)
G
7

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
Grizelda answered 9/1, 2017 at 18:16 Comment(0)
K
0

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
Kolnick answered 9/1, 2017 at 18:23 Comment(0)
C
0

This code will work the way you want:

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

Necessarily the presence of a new line

Chartulary answered 9/1, 2017 at 18:47 Comment(0)
P
0

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')")

Parameter answered 9/1, 2017 at 19:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.