Skip to content

Instantly share code, notes, and snippets.

@viliampucik
Created December 1, 2020 18:05
Show Gist options
  • Save viliampucik/bb33ffd84136d7dedb4c521d5e98b8a8 to your computer and use it in GitHub Desktop.
Save viliampucik/bb33ffd84136d7dedb4c521d5e98b8a8 to your computer and use it in GitHub Desktop.
Python code benchmarking example
#!/usr/bin/env python
# An example of Python code benchmarking.
# In this case math.prod vs functools.reduce(operator.mul).
# As can be seen, math.prod is almost twice as fast as the other option:
#
# ./timeit-test.py
# 4.723656065994874
# 7.586232994995953
# 18.008398708996538
# 31.734708059004333
from operator import mul
from functools import reduce
from math import prod
from itertools import combinations
from random import shuffle
from timeit import timeit
def msolve(numbers, length):
for c in combinations(numbers, length):
prod(c)
def rsolve(numbers, length):
for c in combinations(numbers, length):
reduce(mul, c)
x = list(range(1000))
shuffle(x)
print(timeit(lambda: msolve(x, 2), number=100))
print(timeit(lambda: rsolve(x, 2), number=100))
print(timeit(lambda: msolve(x, 3), number=1))
print(timeit(lambda: rsolve(x, 3), number=1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment