-1

我在模块中有一个读取功能。

如果我同时执行该功能,我需要给它加上时间戳。

我该怎么做呢?

4

4 回答 4

6

我将提供一种稍微不同的方法:

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

与 Swaroop 示例的不同之处在于:

  1. 我使用 time.time() 而不是 datetime.now() 作为时间戳,因为它更适合性能测试
  2. 我将时间戳附加为装饰函数的属性。这样,您可以随时调用并保留它。
于 2009-01-09T07:25:40.163 回答
2
#!/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
于 2009-01-09T06:21:01.137 回答
0

Terik Ziade 的一些示例 代码

(更精致的版本,使用 timeit 模块,可以在他最近出版的《Expert Python Programming》一书中找到)

于 2009-01-09T11:50:52.947 回答
0

如果你有兴趣,python wiki 上有大量关于装饰器的信息

于 2009-01-09T10:27:02.483 回答