-
-
Save nyggus/3dc967d5e88593b624e2acb3e675a62d to your computer and use it in GitHub Desktop.
This file contains 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 perftester | |
from collections import namedtuple | |
from typing import Callable | |
Length = int | |
MemoryBenchmarks = namedtuple("MemoryBenchmarks", "tuple list better") | |
Benchmarks = namedtuple("Benchmarks", "time memory") | |
def benchmark_memory(func_tuple, func_list: Callable) -> Benchmarks: | |
m_tuple = perftester.memory_usage_benchmark(func_tuple) | |
m_list = perftester.memory_usage_benchmark(func_list) | |
better = "tuple" if m_tuple["max"] < m_list["max"] else "list" | |
memory = MemoryBenchmarks(m_tuple["max"], m_list["max"], better) | |
return memory | |
def comprehension(n: Length): | |
"""List comprehension vs tuple comprehension. | |
Here, we're benchmarking two operations: | |
* creating a container | |
* looping over it, using a for loop; nothing is done in the loop. | |
""" | |
def with_tuple(n: Length): | |
x = tuple(i**2 for i in range(n)) | |
for _ in x: | |
pass | |
def with_list(n: Length): | |
x = [i**2 for i in range(n)] | |
for _ in x: | |
pass | |
return benchmark_memory(lambda: with_tuple(n), lambda: with_list(n)) | |
def func_with_range(n: Length) -> MemoryBenchmarks: | |
"""List vs tuple benchmark: func(range(n)).""" | |
def with_tuple(n: Length): | |
return tuple(range(n)) | |
def with_list(n: Length): | |
return list(range(n)) | |
return benchmark_memory(lambda: with_tuple(n), lambda: with_list(n)) | |
def concatenation(n: Length) -> MemoryBenchmarks: | |
"""List vs tuple benchmark: func(range(n)).""" | |
def with_tuple(x: tuple): | |
x += x | |
return x | |
def with_list(y: list): | |
y += y | |
return y | |
return benchmark_memory(lambda: with_tuple(tuple(range(n))), | |
lambda: with_list(list(range(n)))) | |
def repeated_concatenation(n: Length) -> MemoryBenchmarks: | |
"""List vs tuple benchmark: func(range(n)).""" | |
def with_tuple(x: tuple): | |
x *= 5 | |
return x | |
def with_list(y: list): | |
y *= 5 | |
return y | |
return benchmark_memory(lambda: with_tuple(tuple(range(n))), | |
lambda: with_list(list(range(n)))) | |
if __name__ == "__main__": | |
n_set = (5_000_000, 10_000_000) | |
functions_with_n = ( | |
comprehension, | |
func_with_range, | |
concatenation, | |
repeated_concatenation, | |
) | |
results = {} | |
for func in functions_with_n: | |
name = func.__name__ | |
print(name) | |
results[name] = {} | |
for n in n_set: | |
results[name][n] = func(n) | |
perftester.pp(results) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment