Skip to content
Sign upLog in
← Back to Community

Python Snippets #1: Timing Functions

Profile icon
frissynHacker

So... I was really bored today, with no ideas for what to code or motivation to work on my large projects that would take weeks to fully complete, so I decided to compile some snippets of Python code that I use often into a single GitHub repo. I'll share a new one every now and then so that you might learn something or get inspired to work on something new!


First Snippet: @elapsed(function):

The first snippet is a Python decorator that measures the elapsed time during a given function. Simply put, at the start of a function, it'll get the current time, then at the end subtract that from the time it is when the function is finished. It looks like this:

import timeit def elapsed(func): def timed(*args, **kwargs): start = timeit.default_timer() result = func(*args, **kwargs) end = timeit.default_timer() - start print(f"'{func.__name__}' runtime: {start - end}") return result return timed @elapsed def do_stuff(): l = set([i for i in range(100000) if i % 2 == 0]) return l do_stuff()

This code will measure the time it takes for Python to make a set of the even numbers between 0 and 100,000!

Hope you enjoy it!

Voters
Profile icon
KarlPatel
Profile icon
Bookie0
Profile icon
TsunamiOrSumth
Profile icon
frissyn
Comments
hotnewtop
Profile icon
Bookie0

nice!! for the typewriter.py snippet, shouldn't there be another way of calling the function without having to specify how long at the end each time (, 100)? :)

Profile icon
frissyn

eh, it's not that big an inconvenience to pass a number each time you call it, but if you really wanted to you could do something like this:

def typewriter(value: str, p=None): import time pause = typewriter.speed if not p else p for char in value: print(char, end="", flush=True) time.sleep(pause / 1000.0) print(flush=True)

So now you can run the function without declaring a stutter, or set it externally. As an added bonus, passing a stutter will overwrite the attribute you set externally!

typewriter.speed = 120 typewriter("The quick brown fox...") # Goes at 120ms speed typewriter("The quick brown fox...", 90) # Goes at 90ms speed typewriter("The quick brown fox...") # Back at 90ms speed!
Profile icon
Bookie0

@IreTheKID
yay!

typewriter("...jumps over the lazy dog,", 90)
Profile icon
JBloves27

Pretty cool! i think it may be useful for me!

Profile icon
frissyn

:)

Profile icon
JBloves27