Skip to content

Instantly share code, notes, and snippets.

@fhpriamo
Created September 22, 2021 02:05
Show Gist options
  • Save fhpriamo/22fcac9950da278378d716544da3e9bc to your computer and use it in GitHub Desktop.
Save fhpriamo/22fcac9950da278378d716544da3e9bc to your computer and use it in GitHub Desktop.
Some simple profiling.
import cProfile, pstats
import operator
import contextlib
from functools import reduce
from itertools import accumulate
import sys
def cumsum(num=0):
"""Loop based"""
total = 0
for n in range(0, num + 1):
total = total + n
return total
def cumsum2(num=0):
"""Reduced"""
return reduce(operator.__add__, range(0, num + 1), 0)
def cumsum3(num=0):
"""Recursive"""
if num == 0:
return num
return cumsum3(num - 1) + num
def cumsum4(num=0):
"""Memory hungry"""
return list(accumulate(range(0, num + 1)))[-1]
@contextlib.contextmanager
def profile(sort_by=pstats.SortKey.CUMULATIVE):
pr = cProfile.Profile()
pr.enable()
yield
pr.disable()
ps = pstats.Stats(pr).sort_stats(sort_by)
ps.print_stats()
HIGH_WATERMARK = 10000
with profile():
print(cumsum(HIGH_WATERMARK))
with profile():
print(cumsum2(HIGH_WATERMARK))
# high values (say > 10000) will likely cause segmentation faults
if HIGH_WATERMARK < 10000:
sys.setrecursionlimit(HIGH_WATERMARK + 3)
with profile():
print(cumsum3(HIGH_WATERMARK))
with profile():
print(cumsum4(HIGH_WATERMARK))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment