简体   繁体   English

如何在Python中为同时函数调用打上时间戳?

[英]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: 与Swaroop的示例不同之处在于:

  1. I'm using time.time() and not datetime.now() for a timestamp, because it's more suitable for performance testing 我使用time.time()而不是datetime.now()作为时间戳,因为它更适合性能测试
  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 Terik Ziade的一些示例代码

(more polished version, which uses timeit module, can be found in his recent book Expert Python Programming) (使用timeit模块的更完善的版本可以在他的最新著作《专家Python编程》中找到)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python:如何包装函数调用,而不是函数本身? - Python: How do I wrap function calls, not the functions themselves? 如何在调用它的循环条件下调试Python模块函数? - How do I debug a Python module function conditional on a loop that calls it? 如何计算Python 3.6中函数的调用次数? - How do I count the number of calls of a function in Python 3.6? 如何在 python 中获得 2 个联立方程的多个输出? - How do I get multiple outputs for 2 simultaneous equations in python? 我将如何 go 关于计算我的硬件可以处理的 python 脚本的同时调用数? - How would I go about calculating the number of simultaneous calls of my python script my hardware can handle? 如何在python中同时进行组合? (itertools) - How to do simultaneous combinations in python? (itertools) 如何使用 Selenium Python 同时下载 - How to do simultaneous downloads with Selenium Python 如何使用递归编写一个在Python中重复调用另一个函数的函数? - How do I use recursion to write a function that calls another function repeatedly in Python? 如何在 kivy 中进行同步处理? - how can I do Simultaneous process in kivy? 我如何在某个时间戳记时间运行python函数。 没有外部软件? - How do i run a python function at a certain timestamp time. Without outside software?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM