Skip to content

Instantly share code, notes, and snippets.

@nvdv
Created October 4, 2016 10:27
Show Gist options
  • Save nvdv/6553b2e95fb94eea012bc9fda673f7e4 to your computer and use it in GitHub Desktop.
Save nvdv/6553b2e95fb94eea012bc9fda673f7e4 to your computer and use it in GitHub Desktop.
How profilers work - statistical profilers
import defaultdict
import time
import signal
SAMPLE_INTERVAL = 0.001 # seconds
def sample_stack(signum, frame):
stack = []
while frame:
stack.append(frame.f_code.co_name)
frame = frame.f_back
stack_name = '-'.join(reversed(stack))
stats[stack_name] += 1
signal.setitimer(signal.ITIMER_PROF, SAMPLE_INTERVAL)
stats = defaultdict(int)
signal.signal(signal.SIGPROF, sample_stack)
signal.setitimer(signal.ITIMER_PROF, SAMPLE_INTERVAL)
start_time = time.time()
primes = get_primes(1000)
end_time = time.time()
signal.setitimer(signal.ITIMER_PROF, 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment