In [58]:
%autosave 20
%matplotlib inline
import operator
import math
from functools import reduce, lru_cache
# import cProfile
# import timeit
import matplotlib.pyplot as plt
import numpy as np
import numba
In [3]:
N = 8192
In [4]:
%timeit 3 + 5
In [7]:
%%timeit a = np.random.rand(N)
b = a**2
m = np.median(b)
In [13]:
a = np.linspace(0, 1, N)
a += 2
In [14]:
%%timeit l = np.linspace(0, 1, N).tolist()
for i in range(len(l)):
l[i] += 2
In [18]:
%%timeit a = np.linspace(0, 1, N)
for i, x in enumerate(a):
a[i] = 2 + x
In [16]:
%%timeit a = np.linspace(0, 1, N)
a += 2
In [32]:
a = np.random.normal(0, 1, N)
l = a.tolist()
%timeit a.sum()
%timeit np.sum(a)
%timeit reduce(lambda x, y: x+y, l)
%timeit reduce(operator.add, l)
%timeit sum(l)
In [33]:
%%timeit
s = 0
for x in l:
s += x
In [34]:
a = np.random.normal(0, 1, N)
l = a.tolist()
%timeit np.sin(a)
%timeit [math.sin(x) for x in l]
%timeit np.sin(1)
%timeit math.sin(1)
In [42]:
text = ['dsifiafandasadsopjop'] * N
%timeit reduce(operator.add, text)
%timeit ''.join(text)
In [43]:
%%timeit
s = ''
for x in text:
s += x
In [63]:
def golden_ratio_naive(n):
s = 1
for _ in range(n):
s = 1 + 1 / s
return s
def golden_ratio_float(n):
s = 1.
for _ in range(n):
s = 1. + 1. / s
return s
@numba.jit
def golden_ratio_numba(n):
s = 1.
for _ in range(n):
s = 1. + 1. / s
return s
%timeit golden_ratio_naive(100_000)
%timeit golden_ratio_float(100_000)
%timeit golden_ratio_numba(100_000)
In [61]:
def decorator(f):
def g(*args, **kwargs):
return f(*args, **kwargs) + 1
return g
@lru_cache(maxsize=10)
@decorator
def f(x):
print(x)
return x**2
# g = decorator(f)
# g(2)
# decorator(np.sin)(np.pi/2)
In [62]:
print(f(1))
print(f(1))
In [ ]: