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?
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. Note that %%timeit measures the execution time of the entire cell, so the following example includes the time to import NumPy.
repeat() function accepts one extra argument, repeat. The output will be a list of the execution times of all code runs repeated a specified no. of times.
The return value is seconds as a float. It is the total time taken to run the test (not counting the setup), so the average time per test is that number divided by the number argument, which defaults to 1 million.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With