11

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?

5
  • %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. Commented Oct 29, 2019 at 17:10
  • Any examples and documentation avaliable @hpaulj Commented Oct 29, 2019 at 17:43
  • I've used them a lot in my numpy answers Commented Oct 29, 2019 at 18:16
  • 1
    e.g. stackoverflow.com/a/58515904/901925, stackoverflow.com/a/58228285/901925, stackoverflow.com/a/57899108/901925 Commented Oct 29, 2019 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. Commented Aug 20, 2021 at 11:47

1 Answer 1

11

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.