Created
September 22, 2021 02:05
-
-
Save fhpriamo/22fcac9950da278378d716544da3e9bc to your computer and use it in GitHub Desktop.
Some simple profiling.
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 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