python timeit.timer,什么是python中的%timeit?

I always read the code to calculate the time like this way:

%timeit function()

Can you explain what means "%" here?

I think, the "%" is always used to replace something in a string, like %s means replace a string, %d replace a data, but I have no idea about this case.

解决方案

%timeit is an ipython magic function, which can be used to time a particular piece of code (A single execution statement, or a single method)

From the docs:

%timeit

Time execution of a Python statement or expression

Usage, in line mode:

%timeit [-n -r [-t|-c] -q -p

-o] statement

To use it, for example if we want to find out whether using xrange is any faster than using range, you can simply do:

In [1]: %timeit for _ in range(1000): True

10000 loops, best of 3: 37.8 µs per loop

In [2]: %timeit for _ in xrange(1000): True

10000 loops, best of 3: 29.6 µs per loop

And you will get the timings for them.

The major advantage is that you don't have to import timer.timeit, and run the code multiple times to figure out which is the better approach; %timeit will automatically calculate number of runs required for your code based on a total of 2 seconds execution window.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值