小编tly*_*nry的帖子

python:求和的速度

我知道对数字列表求和的最快方法是使用内置函数sum。使用for循环求和可能比使用 更慢reduce。然而,当我尝试时,事实并非如此。有人可以解释这个结果吗?

import time, random, operator

sample = [random.randrange(10000) for _ in range(1000000)]

def use_for(l):
    acc = 0
    for n in l:
        acc += n
    print acc

def use_lambda(l):
    print reduce(operator.add, l)

print time.time()
use_for(l)
print time.time()
use_lambda(l)
print time.time()
Run Code Online (Sandbox Code Playgroud)

我得到的时间:

1479671513.04
4998734199
1479671513.07
4998734199
1479671513.13
Run Code Online (Sandbox Code Playgroud)

python performance

1
推荐指数
1
解决办法
1267
查看次数

标签 统计

performance ×1

python ×1