Search code examples
pythontimejupyter-notebooktimeit

Difference between %time vs %%time vs %timeit %%timeit in Jupyter Notebook


Help me in finding out the exact difference between time and timeit magic commands in jupyter notebook.

%time

a="stack overflow"
time.sleep(2)
print(a)

It shows only some micro seconds, But I added sleep time as 2 seconds


Solution

  • Magics that are prefixed with double percentage signs (%%) are considered cell magics. This differs from line magics which are prefixed with a single percentage sign (%).

    It follows that,

    • time is used to time the execution of code either at a line level (%) or cell level (%%).
    • timeit is similar but runs the code multiple times to provide more accurate and statistically significant timing information.

    The key distinction is that %time and %%time (docs) measure the execution time of code once, while %timeit and %%timeit (docs) measure the execution time of code multiple times to give an average time and standard deviation.

    Hence,

    %%time
    
    a="stack overflow"
    time.sleep(2)
    print(a)
    

    This output shows both the CPU time and the wall time. The wall time includes the 2 seconds sleep time, while the CPU time accounts for the actual processing time.

    Replacing %%time with %time will show the CPU time and the wall time for the next single line that is executed.