Skip to content

Instantly share code, notes, and snippets.

@Tuhin-thinks
Last active January 13, 2026 07:09
Show Gist options
  • Select an option

  • Save Tuhin-thinks/43d42396890fe1ba53579cf9cf02800f to your computer and use it in GitHub Desktop.

Select an option

Save Tuhin-thinks/43d42396890fe1ba53579cf9cf02800f to your computer and use it in GitHub Desktop.
Profile code execution time
import time
import typing
from functools import wraps
def profiler(fn: typing.Callable):
"""to be used as a function decorator for monitoring execution time of a function"""
@wraps(fn)
def inner():
start_time = time.perf_counter_ns()
fn()
elapsed = time.perf_counter_ns() - start_time
print(f"Elapsed: {elapsed / 10**6:.03f} on function {fn.__name__}")
return inner()
class ProfilerContext:
"""can be used as a context manager, with start and stop utility functions for starting and stopping point usage
if using without context manager, just to record time spent between 2 points.
"""
def __init__(self, name: str):
self.name = name
def __enter__(self):
self._start = time.perf_counter_ns()
def __exit__(self, exc_type, exc_val, exc_tb):
elapsed = (time.perf_counter_ns() - self._start) / 10**6
print(
f"Elapsed: {elapsed:.03f}ms",
end="" or f", (or {elapsed / 1000:.02f} secs.), "
if elapsed > 1000
else " ",
)
print(f'on "{self.name}"')
def start(self):
self.__enter__()
def stop(self):
self.__exit__(None, None, None)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment