Han
Han

Reputation: 59

How do you use %timeit on a .py file?

%timeit sortThis 
Output: 15.1 ns ± 0.163 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)

Tried this but it's not giving me the right output.

sortThis is a .py file with a simple function that sorts a list. I've timed it with a stopwatch and it's way more than what the command is returning.

Thank you for your help.

EDIT: This is for a homework assignment and I must use %timeit in the command line.

Upvotes: 5

Views: 5862

Answers (2)

Rory Daulton
Rory Daulton

Reputation: 22544

In my IPython console (IPython 6.4.0 with Python 3.6.5, installed under Anaconda 5.2), this works.

%timeit %run sortThis

Be careful of several things. Use the %cd magic command to make sure your current working directory is the one holding the sortThis script. Either that, or include the path to the script in your command. Also, if the script prints anything, you could end up with hundreds or thousands of copies of the printing in your console before %timeit shows its results.

When I had just the command print('Hello, world!') in the sortThis script, I got this result:

1.23 ms ± 5.97 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

I'm pretty sure that the first load of the script caused Python saved the compiled version to a .pyc file and and that file was in my computer's cache. So the stated time averaged all that over many executions, resulting in a small time interval. So don't expect %timeit to time your first execution of the script--just the average over many consecutive executions.

Upvotes: 6

Patrick Haugh
Patrick Haugh

Reputation: 60994

Define an entry point for your script, a function into which you move all of the stuff that was at the top-level of the script. If your old script is

import someStuff

def doStuff(y):
    return someStuff.stuff(y)

x = 100   
print(doStuff(x))

Then your new script would be

import someStuff

def doStuff(y):
    return someStuff.stuff(y)

def main():
    x = 100   
    print(doStuff(x))

if __name__ == '__main__':  
    main()

if __name__ == '__main__' makes the script still runnable directly.

Then just do %timeit yourfile.main()

Upvotes: 1

Related Questions