计算列表平均值的最快方法

时间:2019-09-19 18:09:11

标签: python python-2.7

我想找到最快的方法来计算python INSERT INTO <TABLE_NAME> VALUES(<COL1,COL2,COL3>,....etc) SELECT * FROM <TABLE_NAME> // this select query retrieves 1 million records 的平均值。我在list中存储了数百万个list,因此我正在寻找性能方面最有效的方法。

引用this question, 如果dictionary是浮点数列表,那么我有

  • l
  • numpy.mean(l)
  • sum(l) / float(len(l))

哪种方法最快?

2 个答案:

答案 0 :(得分:1)

正如@DeepSpace所建议的那样,您应该尝试自己回答这个问题。您还可以考虑在使用numpy.mean之前将列表转换为数组。将%timeitipython一起使用,如下所示:

In [1]: import random
In [2]: import numpy
In [3]: from functools import reduce
In [4]: l = random.sample(range(0, 100), 50) # generates a random list of 50 elements

numpy.mean而不转换为np.array

In [5]: %timeit numpy.mean(l)
32.5 µs ± 2.82 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

numpy.mean转换为np.array

In [5]: a = numpy.array(a)
In [6]: %timeit numpy.mean(a)
17.6 µs ± 205 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

sum(l) / float(len(l))

In [5]: %timeit sum(l) / float(len(l)) # not required casting (float) in Python 3
774 ns ± 20.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

sum(l) / float(len(l))

In [5]: %timeit sum(l) / len(l)
623 ns ± 27.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

reduce

In [6]: reduce(lambda x, y: x + y, l) / len(l)
5.92 µs ± 514 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

从最慢到最快:

  1. numpy.mean(l)而不转换为数组
  2. numpy.mean(a)将列表转换为np.array
  3. reduce(lambda x, y: x + y, l) / len(l)
  4. sum(l) / float(len(l)),这适用于Python 2和3
  5. sum(l) / len(l)#对于Python 3,不需要强制转换(使用float

答案 1 :(得分:0)

下午好, 我只是用列表中的10个随机浮点数进行了测试,然后进行了时间测试,发现numpy最快。

#!/usr/bin/python

import numpy as np
from functools import reduce
import time

l = [0.1, 2.3, 23.345, 0.9012, .002815, 8.2, 13.9, 0.4, 3.02, 10.1]

def test1():
    return np.mean(l)

def test2():
    return sum(l) / float(len(l))

def test3():
    return reduce(lambda x, y: x + y, l) / len(l)

def timed():
    start = time.time()
    test1()
    print('{} seconds'.format(time.time() - start))
    start = time.time()
    test2()
    print('{} seconds'.format(time.time() - start))
    start = time.time()
    test3()
    print('{} seconds'.format(time.time() - start))

timed()

和往常一样,我敢肯定有更好的方法可以做到这一点,但这可以解决问题。 这是一个很小的列表:看到大列表会很有趣。

相关问题