7

What difference does it make to use %timeit and %%timeit in ipython? Because when I read the documentation using ?%timeit and ?%%timeit it was the same documentation. So, what difference does adding % as prefix make?

bigbounty
  • 16,526
  • 5
  • 37
  • 65
  • `%magic` is a line magic, which uses input on the same line. `%%magic` is a cell magic, which takes multiline input. I use `%timeit` to test a simple expression. I use `%%timeit to do setup on the first line, and the following lines to a multiline expression. – hpaulj Oct 29 '19 at 17:10
  • Any examples and documentation avaliable @hpaulj – bigbounty Oct 29 '19 at 17:43
  • I've used them a lot in my numpy answers – hpaulj Oct 29 '19 at 18:16
  • 1
    e.g. https://stackoverflow.com/a/58515904/901925, https://stackoverflow.com/a/58228285/901925, https://stackoverflow.com/a/57899108/901925 – hpaulj Oct 29 '19 at 20:15
  • It would be useful to have a more general question about the difference between `%` and `%%` in ipython, that doesnt' focus just on `timeit`, and a good answer that explains the difference between line magic and cell magic. If you google it the results are awful. – eric Aug 20 '21 at 11:47

1 Answers1

7

In general, one percentage sign is referred to as line magic and applies just to code that follows it on that same line. Two percentage signs is referred to as cell magic and applies to everything that follows in that entire cell.

As nicely put in The Data Science Handbook:

Magic commands come in two flavors: line magics, which are denoted by a single % prefix and operate on a single line of input, and cell magics, which are denoted by a double %% prefix and operate on multiple lines of input.

Some magic commands, like timeit, can work as line magic or cell magic:

Used as line magic:

%timeit y = 2 if x < 3 else 4

Used as cell magic:

%%timeit
if x < 3:
    y=2
else:
    y=4
eric
  • 7,142
  • 12
  • 72
  • 138