Package: time-magics
Time-magicsiPython%timeand%timeitmagic command in normal Python files.importtimeimporttime_magicsastmdeffoo(n):time.sleep(0.1)returnsum(list(range(n)))tm.time("foo(1_000_000)",ns={"foo":foo})tm.timeit("foo(1_000_000)",ns={"foo":foo})>>CPUtimes:user18.9ms,sys:23.8ms,total:42.7msWalltime:143ms138ms±1.46msperloop(mean±std.dev.of7runs,10loopseach)Time-magics allows you to time code in a.pyfile with the same output and behavior as the%timeitand%timecommand in iPython and Jupyter Notebook.It also provides the functionstime_andtimeit_, which allows you to time a function by
decorating it:importtimeimporttime_magicsastm@tm.timeit_deffoo(n):returnsum(list(range(n)))@tm.time_defbar(n):time.sleep(0.5)returnsum(list(range(n)))# Both timeit_ and timeit returns a TimeitResult objectresult=foo(10_000)print("timeit_ output:",type(result),result.best)# While time_ and time returns the timed statement return value (if any)value=bar(10_000)print("time_ output:",value)>>97.6µs±825nsperloop(mean±std.dev.of7runs,10000loopseach)timeit_output:<TimeitResult>9.643386240350083e-05CPUtimes:user668µs,sys:2µs,total:670µsWalltime:501mstime_output:49995000It should be noted thattimeit()andtimeit_()returns aTimeitResultobject, whiletime()andtime_()returns the statement return value.For more usage information, consult the function docstrings.InstallationTime-magics is available onPyPI:python -m pip install time-magicsUsageThensparameter specifies a namespace in which to execute the code:>>>importtime>>>importtime_magicsastm>>>tm.timeit("time.sleep(0.5)")NameError:name'time'isnotdefined>>>tm.timeit("time.sleep(0.5)",ns={'time':time})501ms±24.9µsperloop(mean±std.dev.of7runs,1loopeach)timeit()andtimeit_()has the two optional parametersnandrwhich does the same
as in%timeit:n- How many times to executestmt. Ifnis not provided, it will determined so as
to get sufficient accuracy.r- Number of repeats, each consisting ofnloops, and take the best result.importtime_magicsastmtm.timeit('sum(list(range(100)))')tm.timeit('sum(list(range(100)))',r=3,n=1000)>>1.83µs±17nsperloop(mean±std.dev.of7runs,100,000loopseach)1.84µs±14nsperloop(mean±std.dev.of3runs,1,000loopseach)PitfallsFor multi-line statementstime()andtimeit()will run in cell mode (i.e.%%time[it]instead of%time[it]). There is a subtle, but crucial difference in behavior between the
two functions in cell mode:timeit()will run the first line in the statement string as setup code and is executed, but not
timed. All lines after the setup line are considered the body of the cell and are timed.time(), on the other hand, doesn't use the first line as setup code when running multiple
lines. The first line will therefore be timed as normal.Both functions behavior reflects their magic command equivalents.importtimeimporttime_magicsastmstmt="""time.sleep(1)time.sleep(1)"""tm.timeit(stmt,ns={'time':time})tm.time(stmt,ns={'time':time})>>1s±233µsperloop(mean±std.dev.of7runs,1loopeach)# Only the last time.sleep is timed, the first line is used as setupCPUtimes:user216µs,sys:15µs,total:231µsWalltime:2s# Both time.sleeps is timedYou should passstmtas a raw string if it contains strings with newline (\n) characters.
If not,stmtmay be incorrectly parsed. For example:>>>importtime_magicsastm>>>tm.time("a = 'This\nwill\nfail\nto\nrun'")SyntaxError:unterminatedstringliteral(detectedatline1)>>>tm.time(r"a = 'This \n will \n run \n as \n expected'")CPUtimes:user2µs,sys:0ns,total:2µsWalltime:1.91µs>>>tm.time("a = 'This\\n will\\n also\\n run\\n as\\n expected'")CPUtimes:user1µs,sys:0ns,total:1µsWalltime:2.15µs