如何在Python中同步函数调用的时间戳?

use*_*646 -1 python function-call timestamping simultaneous-calls

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

如果我同时执行该功能,我需要为其加时间戳.

我该怎么做呢?

Eli*_*sky 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
Run Code Online (Sandbox Code Playgroud)

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

  1. 我使用time.time()而不是datetime.now()作为时间戳,因为它更适合于性能测试
  2. 我将时间戳作为装饰函数的属性附加.这样您就可以随时调用并保留它.