Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use else inside Python's timeit

Tags:

python

timeit

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?

like image 637
Pro Q Avatar asked Jan 09 '17 18:01

Pro Q


People also ask

What does %% Timeit do in Python?

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.

How do you repeat Timeit?

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.

What unit does Timeit use?

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.


1 Answers

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
like image 65
Uriel Avatar answered Nov 01 '22 15:11

Uriel