Created
April 8, 2023 02:41
-
-
Save onlyphantom/4f9a848a7210224d9b5745a98caaf030 to your computer and use it in GitHub Desktop.
Code demo for https://youtu.be/xgIkRcYY70k
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
import numpy as np | |
def timeit(): | |
""" | |
a utility decoration to time running time | |
""" | |
def decorator(func): | |
def wrapper(*args, **kwargs): | |
start = time.time() | |
func(*args, **kwargs) | |
end = time.time() | |
print(f"running time: {end - start} secs") | |
return end - start | |
return wrapper | |
return decorator | |
@timeit() | |
def add_iteratively(n): | |
""" | |
add numbers up to n | |
""" | |
sum = 0 | |
for i in range(n + 1): | |
sum += i | |
print(sum) | |
@timeit() | |
def add_vectorize(n): | |
""" | |
add numbers up to n | |
""" | |
sum = np.sum(np.arange(n + 1)) | |
print(sum) | |
@timeit() | |
def add_mul_iteratively(v, w, b): | |
out = np.zeros(len(v)) | |
for i in range(len(v)): | |
out[i] = v[i] * w[i] + b | |
@timeit() | |
def mul_vectorize(v, w, b): | |
v * w + b | |
@timeit() | |
def dot_iteratively(x, m): | |
""" | |
matrix multiplication of x and m without using numpy | |
m = np.array([[1, 2, 3, 4, 5]]) | |
x = np.random.rand(7, 5) | |
""" | |
out = np.zeros(x.shape[0]) | |
total = 0 | |
for i in range(x.shape[0]): | |
total = 0 | |
for j in range(x.shape[1]): | |
total += x[i][j] * m[0][j] | |
out[i] = total | |
# print(out) | |
@timeit() | |
def dot_vectorize(x, m): | |
# print(x.dot(m.T)) | |
x.dot(m.T) | |
@timeit() | |
def tim_solution(x): | |
x.rotate(3) | |
@timeit() | |
def optim_solution(x): | |
x.rotate(-2) | |
if __name__ == "__main__": | |
from collections import deque | |
x = deque(range(5), maxlen=5) | |
a = tim_solution(x) | |
b = optim_solution(x) | |
print(f"A magnitude of {a // b} difference") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment