I have a read function in a module.
If I perform that function simultaneously I need to timestamp it.
How do I do this?
I have a read function in a module.
If I perform that function simultaneously I need to timestamp it.
How do I do this?
#!/usr/bin/env python
import datetime
def timestampit(func):
def decorate(*args, **kwargs):
print datetime.datetime.now()
return func(*args, **kwargs)
return decorate
@timestampit
def hello():
print 'hello'
hello()
# Output:
# $ python test.py
# 2009-01-09 11:50:48.704584
# hello
I'll offer a slightly different approach:
import time
def timestampit(func):
def decorate(*args, **kwargs):
decorate.timestamp = time.time()
return func(*args, **kwargs)
return decorate
@timestampit
def hello():
print 'hello'
hello()
print hello.timestamp
time.sleep(1)
hello()
print hello.timestamp
The differences from Swaroop's example are:
If you're interested, there's a wealth of information about decorators on the python wiki.
Some example code by Terik Ziade
(more polished version, which uses timeit module, can be found in his recent book Expert Python Programming)