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'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:
#!/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
如果您有兴趣,可以在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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.