Skip to content

Instantly share code, notes, and snippets.

@thuwarakeshm
Last active May 27, 2022 14:59
Show Gist options
  • Save thuwarakeshm/40021dfc3fc32eeab65bf09829ebce0c to your computer and use it in GitHub Desktop.
Save thuwarakeshm/40021dfc3fc32eeab65bf09829ebce0c to your computer and use it in GitHub Desktop.
Python benchmarking
import random
from timeit import timeit
from typing import List
def bubble_sort(items: List[int]) -> List[int]:
n = len(items)
for i in range(n - 1):
for j in range(0, n - i - 1):
if items[j] > items[j + 1]:
items[j], items[j + 1] = items[j + 1], items[j]
numbers = [random.randint(1, 10000) for i in range(1000000)]
print(timeit(lambda:bubble_sort(numbers),number=5))
import pickle
from typing import List
def bubble_sort(l:List[int]):
n = len(l)
for i in range(n - 1):
for j in range(0, n - i - 1):
if l[j] > l[j + 1]:
l[j], l[j + 1] = l[j + 1], l[j]
def sort_array():
with open('array.pkl', 'rb') as f:
l = pickle.load(f)
return bubble_sort(l)
def fib(n: int) -> int:
return n if n < 2 else fib(n - 1) + fib(n - 2)
from glob import glob
from timeit import timeit
file_paths = glob("./data/*.txt")
statement = f"""
for path in {file_paths}:
with open(path, "r") as f:
f.read()
"""
print(timeit(statement, number=10))
from timeit import timeit
statement = """
for i in range(100000):
with open(f"./data/a{i}.txt", "w") as f:
f.write('a')
"""
print(timeit(statement, number=10))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment