简体   繁体   中英

How do I timestamp simultaneous function calls in Python?

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:

  1. I'm using time.time() and not datetime.now() for a timestamp, because it's more suitable for performance testing
  2. I'm attaching the timestamp as an attribute of the decorated function. This way you may invoke and keep it whenever you want.
#!/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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM