如何在 Python 中为同时调用的函数添加时间戳?

发布于 2024-07-11 16:27:01 字数 71 浏览 5 评论 0原文

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

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

我该怎么做呢?

I have a read function in a module.

If I perform that function simultaneously I need to timestamp it.

How do I do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

单身狗的梦 2024-07-18 16:27:01

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

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

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.
子栖 2024-07-18 16:27:01
#!/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
#!/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
安稳善良 2024-07-18 16:27:01

一些例子
Terik Ziade 的代码

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

Some example
code by Terik Ziade

(more polished version, which uses timeit module, can be found in his recent book Expert Python Programming)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文