-
Notifications
You must be signed in to change notification settings - Fork 26
/
sum.py
77 lines (57 loc) · 1.78 KB
/
sum.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
"""
Given a list of numbers, compute their sum.
"""
import pandas as pd
from numba import jit
import numpy as np
from typing import List
from utils.profiler import time_this, timed_report
from utils.profiler import ExponentialRange
def random_numeric_list(n: int) -> List[np.float64]:
return list(np.random.random(n))
@time_this(lambda x: len(x))
def fast_sum(values: List[float]) -> float:
accum = 0
for value in values:
accum += value
return accum
@time_this(lambda x: len(x))
def fast_native_sum(values: List[float]) -> float:
return sum(values)
@time_this(lambda x: len(x))
def numpy_fast_sum(values: np.ndarray) -> float:
return np.sum(values)
@time_this(lambda x: len(x))
def pandas_fast_sum(values: pd.Series) -> float:
return values.sum()
@jit(nopython=True)
def _numba_fast_sum(values: np.ndarray) -> float:
"""
JIT compilation occurs after one use
"""
accum = 0
for value in values:
accum += value
return accum
# Force numba to run jit compilation
_numba_fast_sum(np.array(random_numeric_list(100000)))
@time_this(lambda x: len(x))
def numba_fast_sum(values: np.ndarray) -> float:
"""
Redeclare optimized wrapper
"""
return _numba_fast_sum(values)
if __name__ == '__main__':
exp_range = ExponentialRange(0, 8, 1/4)
values = random_numeric_list(exp_range.max)
with timed_report():
for i in exp_range.iterator():
fast_sum(values[:i])
for i in exp_range.iterator():
fast_native_sum(values[:i])
for i in exp_range.iterator():
numpy_fast_sum(np.array(values[:i]))
for i in exp_range.iterator():
pandas_fast_sum(pd.Series(values[:i]))
for i in exp_range.iterator():
numba_fast_sum(np.array(values[:i]))