Skip to content

Instantly share code, notes, and snippets.

@guimello
Created July 11, 2013 01:48
Show Gist options
  • Save guimello/5971863 to your computer and use it in GitHub Desktop.
Save guimello/5971863 to your computer and use it in GitHub Desktop.
Decorators examples in python.
from time import time
# Decoratoring with a class
class Benchmark(object):
def __init__(self, function):
self.function = function
def __call__(self, *args, **kwargs):
t1 = time()
result = self.function(*args, **kwargs)
t2 = time()
diff = t2 - t1
measure = "sec(s)"
if diff < 1:
measure = "ms"
diff *= 1000
print "Execution time: %.2f %s" % (diff, measure)
return result
# Decoratoring with a function
def benchmark(function):
def _benchmark(*args, **kwargs):
t1 = time()
result = function(*args, **kwargs)
t2 = time()
diff = t2 - t1
measure = "sec(s)"
if diff < 1:
measure = "ms"
diff *= 1000
print "Execution time: %.2f %s" % (diff, measure)
return result
return _benchmark
from decorators import *
# Class decorator example
@Benchmark
def take_time(n):
for i in xrange(0, n):
pass
# Function decorator example
@benchmark
def take_time2(n):
for i in xrange(0, n):
pass
take_time(1) #=> Execution time: 0.00 ms
take_time(100000000) #=> Execution time: 3.01 sec(s)
take_time2(1) #=> Execution time: 0.00 ms
take_time2(100000000) #=> Execution time: 3.01 sec(s)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment