Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python timeit and program output

Is there any way to use the timeit function to output both the function result and the time it took to process at the same time?

Right now I am using

timer = Timer('func()', 'from __main__ import func')
print timer.timeit(1)

But this just outputs the time and not the program output, which returns something at its end. I want it to output

FuncOutputGoesHere 13.2897528935

on the same line.

Ideally, I'd like to be able to take an average of the program by running it N times and then outputting the program result and its average time (a total of one output overall)

like image 301
MyNameIsKhan Avatar asked Jun 04 '12 16:06

MyNameIsKhan


People also ask

What does Python Timeit return?

The timeit() method returns the amount of time it takes to execute the statement repeatedly. The output of show_results() converts that into the amount of time it takes per iteration, and then further reduces the value to the average amount of time it takes to store one item in the dictionary.

How do I print a Timeit in Python?

The syntax to execute your function inside timeit() on the command line is as follows: python -m timeit [-n N] [-r N] [-s S] [-t] [-c] [-h] [code statement ...] Command line parameters: -n N: the number of times you want the code to execute.

How do you use %% Timeit in Jupyter?

The “%timeit” is a line magic command in which the code consists of a single line or should be written in the same line for measuring the execution time. In the “%timeit” command, the particular code is specified after the “%timeit” is separated by a space.


1 Answers

Two options:

  1. Include 'print' in your timed code. Ugly, but hey.

    timer = Timer('print func()', 'from __main__ import func')
    print timer.timeit(1)
    
  2. If all you do is run your function once, then dispense with the timeit module altogether and time the code directly using the same method:

    import sys
    import time
    
    if sys.platform == "win32":
        # On Windows, the best timer is time.clock()
        default_timer = time.clock
    else:
        # On most other platforms the best timer is time.time()
        default_timer = time.time
    
    t0 = default_timer()
    output = func()
    t1 = default_timer()
    print output, t1 - t0
    

If you want to run the code multiple times, and produce the output, why not run the code once outside the timeit function? You are calling it more than once then already anyway:

    timer = Timer('func()', 'from __main__ import func')
    print timer.timeit(100),
    print func()
like image 200
Martijn Pieters Avatar answered Sep 25 '22 01:09

Martijn Pieters