Skip to content

Instantly share code, notes, and snippets.

@avyfain
Last active December 25, 2016 21:57
Show Gist options
  • Save avyfain/758b8a2e35d3a75a21253f2ff4fddb42 to your computer and use it in GitHub Desktop.
Save avyfain/758b8a2e35d3a75a21253f2ff4fddb42 to your computer and use it in GitHub Desktop.
Calculating averages efficiently, using Python
# Timing script to compare various ways to compute the mean of list of ints
# Short explanation, and results of the experiment can be found here:
# www.faingezicht.com/articles/2016/12/25/means/
import random
import timeit
import statistics
import numpy as np
random.seed(1)
lengths = [10, 100, 1000]
lsts = [[random.randint(0, 100) for _ in range(length)] for length in lengths]
def mean1(lst):
num = 0
denom = 0
for i in range(len(lst)):
num += lst[i]
denom += 1
return num/denom
def mean2(lst):
numer = 0
denom = 0
for num in lst:
numer += num
denom += 1
return numer/denom
def mean3(lst):
return sum(lst) / len(lst)
def numpy(lst):
return np.mean(lst)
def stats(lst):
return statistics.mean(lst)
funcs = [mean1, mean2, mean3, numpy, stats]
if __name__ == '__main__':
for lst in lsts:
print("\nLists of length", len(lst))
for f in funcs:
print(f.__name__, timeit.timeit('f(lst)', "from __main__ import f, lst"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment