【问题标题】:How do I timestamp simultaneous function calls in Python?如何在 Python 中为同时函数调用添加时间戳?
【发布时间】:2009-01-09 05:21:49
【问题描述】:

我在一个模块中有一个读取函数。

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

我该怎么做?

【问题讨论】:

  • 请提供更多细节。时间戳应该记录在哪里?你是从文件中读取吗?您是说时间戳必须与读取功能同时进行,还是说如果同时发生读取则需要时间戳?
  • 给函数加时间戳是什么意思?
  • 同步是什么意思?
  • “同时”没有任何意义。即使有多个线程,在给定时间实际上也只有一个被调度。如果是跨多个进程,那就不是“同一个”函数,是两份,每个进程一份。

标签: python function-call timestamping simultaneous-calls


【解决方案1】:

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

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. 我将时间戳作为修饰函数的属性附加。这样您就可以随时调用并保留它。

【讨论】:

  • 他在询问函数的同时调用。使用这种方法,稍晚一点的调用将覆盖之前调用的时间戳。
  • 是的,但这是一个具有相同功能的故意示例。他可以装饰两种不同的功能。坦率地说,同时是什么意思??
  • 对,我很确定他没有谈论线程或其他并行化技术。但在没有其他解释“同时”可能意味着什么的情况下,我想,我会在这里提一下。
【解决方案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

【讨论】:

  • 我是 Python 的初学者。请不要介意我的问题。你能解释一下发生了什么吗,Swaroop???
  • @rejinacm,我们正在使用装饰器,你可以read about it in this introduction
【解决方案3】:

【讨论】:

    【解决方案4】:

    一些例子 code by Terik Ziade

    (更精致的版本,使用了timeit模块,可以在他最近的《Python编程专家》一书中找到)

    【讨论】:

      猜你喜欢
      • 2018-04-29
      • 2018-09-19
      • 2019-10-18
      • 1970-01-01
      • 2023-04-02
      • 2016-10-23
      • 2017-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多