2

The magic command %time produces the time it takes to execute a given code segment (statement) to the output cell in Jupyter Notebook. I would like this to be appended on to a specified file instead.

My objective is to find the runtime of an algorithm in different settings. I am able to automate the parameters of the algorithm, although not able to store the output of the %time (and %timeit) magic command in a file for further processing.

Is this possible?

Thomas K
  • 39,200
  • 7
  • 84
  • 86
Ébe Isaac
  • 11,563
  • 17
  • 64
  • 97
  • `%timeit` (but not `%time`) has a `-o` option which makes it return an object, so you can do `res = %timeit -o foo()`. Then you can get the numbers from res and write them to a file however you wish. For more flexibility, use the [timeit module](https://docs.python.org/3/library/timeit.html) in the standard library. – Thomas K Nov 19 '16 at 15:50
  • @ThomasK That's nice. I'd be happier if you could post this comment as an answer. – Ébe Isaac Nov 19 '16 at 16:21

1 Answers1

5

Reposting as an answer:

%timeit (but not %time) has a -o option which makes it return an object, so you can do:

res = %timeit -o foo()

Then you can get the numbers from res and write them to a file however you wish.

For more flexibility, use the timeit module in the standard library.

Thomas K
  • 39,200
  • 7
  • 84
  • 86