mul python_python – int .__ mul__,比operator.mul慢2倍

如果你看下面的时间:

C:\Users\Henry>python -m timeit -s "mul = int.__mul__" "reduce(mul,range(10000))"

1000 loops, best of 3: 908 usec per loop

C:\Users\Henry>python -m timeit -s "from operator import mul" "reduce(mul,range(10000))"

1000 loops, best of 3: 410 usec per loop

执行速度之间有显着差异

reduce(int .__ mul __,range(10000))和reduce(mul,range(10000)),后者更快.

使用dis模块来查看发生了什么:

使用int .__ mul__方法:

C:\Users\Henry>python

Python 2.7.4 (default, Apr 6 2013, 19:55:15) [MSC v.1500 64 bit (AMD64)] on win32

Type "help", "copyright", "credits" or "license" for more information.

>>> mul = int.__mul__

>>> def test():

... mul(1,2)

...

>>> import dis

>>> dis.dis(test)

2 0 LOAD_GLOBAL 0 (mul)

3 LOAD_CONST 1 (1)

6 LOAD_CONST 2 (2)

9 CALL_FUNCTION 2

12 POP_TOP

13 LOAD_CONST 0 (None)

16 RETURN_VALUE

>>>

和运算符mul方法

C:\Users\Henry>python

Python 2.7.4 (default, Apr 6 2013, 19:55:15) [MSC v.1500 64 bit (AMD64)] on win32

Type "help", "copyright", "credits" or "license" for more information.

>>> from operator import mul

>>> def test():

... mul(1,2)

...

>>> import dis

>>> dis.dis(test)

2 0 LOAD_GLOBAL 0 (mul)

3 LOAD_CONST 1 (1)

6 LOAD_CONST 2 (2)

9 CALL_FUNCTION 2

12 POP_TOP

13 LOAD_CONST 0 (None)

16 RETURN_VALUE

>>>

它们看起来是一样的,为什么执行速度有差异?我指的是Python的CPython实现

在python3上也是如此:

$python3 -m timeit -s 'mul=int.__mul__;from functools import reduce' 'reduce(mul, range(10000))'

1000 loops, best of 3: 1.18 msec per loop

$python3 -m timeit -s 'from operator import mul;from functools import reduce' 'reduce(mul, range(10000))'

1000 loops, best of 3: 643 usec per loop

$python3 -m timeit -s 'mul=lambda x,y:x*y;from functools import reduce' 'reduce(mul, range(10000))'

1000 loops, best of 3: 1.26 msec per loop

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值