Skip to content

Instantly share code, notes, and snippets.

Created October 18, 2022 21:46
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save eliemichel/54245eacf9bef18914a8c07ceb0af503 to your computer and use it in GitHub Desktop.
A minimal profiling module
# Credits 2020-2022 to Élie Michel <>
# Released in Public Domain
# The Software is provided "as is", without warranty of any kind, express or
# implied, including but not limited to the warranties of merchantability,
# fitness for a particular purpose and non-infringement. In no event shall the
# authors or copyright holders be liable for any claim, damages or other
# liability, whether in an action of contract, tort or otherwise, arising
# from, out of or in connection with the software or the use or other dealings
# in the Software.
from math import sqrt
import time
from collections import defaultdict
# -------------------------------------------------------------------
class Timer():
def __init__(self):
self.start = time.perf_counter()
def ellapsed(self):
return time.perf_counter() - self.start
# -------------------------------------------------------------------
class ProfilingCounter:
def __init__(self):
def average(self):
if self.sample_count == 0:
return 0
return self.accumulated / self.sample_count
def stddev(self):
if self.sample_count == 0:
return 0
avg = self.average()
var = self.accumulated_sq / self.sample_count - avg * avg
return sqrt(max(0, var))
def add_sample(self, value):
if hasattr(value, 'ellapsed'):
value = value.ellapsed()
self.sample_count += 1
self.accumulated += value
self.accumulated_sq += value * value
def reset(self):
self.sample_count = 0
self.accumulated = 0.0
self.accumulated_sq = 0.0
def summary(self):
"""returns something like XXms (±Xms, X samples)"""
return (
f"{self.average()*1000.:.03}ms " +
f"(±{self.stddev()*1000.:.03}ms, " +
f"{self.sample_count} samples)"
# -------------------------------------------------------------------
profiling_counters = defaultdict(ProfilingCounter)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment