python timeit用法_python中的时间与%timeit %% timeit如何保留/保留值供以后使用

I am trying to measure the execution time of different parts of my code, a few lines each. I am doing this with %%timeit, however after I execute a cell, I find that the values calculated for variables in the cell are not kept in memory for next cells, as in the following example.

Why does this happen? Is there a way to retain the values so I can use them in the rest of the program?

In [1]: %%timeit

...: dog='dog'

100000000 loops, best of 3: 16.2 ns per loop

In [2]: print (dog)

---------------------------------------------------------------------------

NameError Traceback (most recent call last)

in ()

----> 1 print (dog)

NameError: name 'dog' is not defined

This sounds like an apparently trivial question to me (or what I would expect as default behavior), but I wasn't able to find any information online, so I hope someone can help.

解决方案

Just ran this:

%%timeit

dog='dog'

for i in range(100000000):

i += 1

print(i)

print(dog)

in a jupyter notebook online and it gave:

100000000

dog

100000000

dog

100000000

dog

100000000

dog

100000000

dog

100000000

dog

100000000

dog

100000000

dog

6.6 s ± 123 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

try it.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值