简体   繁体   English

魔术功能时间

[英]Magic function timeit

I'm using the magic %%timeit function to get the time it takes to execute some code. 我正在使用神奇的%% timeit函数来获取执行某些代码所花费的时间。 The thing that bothers me is that when I run %%timeit, I don't get the results. 让我困扰的是,当我运行%% timeit时,我没有得到结果。 For instace: 对于实例:

a=5
b=3

%%timeit
c = a + b

Now if I want to use c in the next cell, I get that c hasn't been defined. 现在,如果我想在下一个单元格中使用c,我会得到尚未定义c的信息。

print(c)
>>>NameError: name 'c' is not defined

Could you help me understand why this happens, why doesn't c get stored when the magic %%timeit function is used in that particular cell? 您能帮我理解为什么会发生这种情况吗,为什么在该特定单元格中使用不可思议的%% timeit函数时不保存它?

当您使用%%timeit计时代码时,您提供的代码将在单独的命名空间中执行,因此其效果对您的环境不可见。

cell mode: 电池模式:

 %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code code code... 

In cell mode, the statement in the first line is used as setup code (executed but not timed) and the body of the cell is timed. 在单元模式下,第一行中的语句用作设置代码(已执行但未计时),并且单元的主体已计时。 The cell body has access to any variables created in the setup code. 单元主体可以访问在设置代码中创建的任何变量。

https://ipython.org/ipython-doc/3/interactive/magics.html#magic-timeit https://ipython.org/ipython-doc/3/interactive/magics.html#magic-timeit

You're executing in cell mode, and the line is just setup code ; 您在单元模式下执行,该行只是设置代码 which means it's not actually timed and its results are only accessible to the cell code following it. 这意味着它实际上并未计时,其结果只能由其后的单元格代码访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM