Warning: ftp_fget() expects parameter 1 to be resource, null given in /www/wwwroot/new.weijing.co/wp-admin/includes/class-wp-filesystem-ftpext.php on line 146

Python 中如何计算某段代码的运行时长

有些代码执行时间较久,我们希望能够计算出其实际运行时长。可以采用 datetime 库。
(1) 定义一个计算方法:

import datetime
def print_cost(start_time):
    \'\'\'
    计算耗时时长
    :param start_time:开始时间
    :return: 耗时时长,精确到 s
    \'\'\'
    end_time = datetime.datetime.now()
    print(\'共耗时:\' + str(end_time - start_time).split(\'.\')[0] + \'。\')

(2) 使用模板:

import datetime
...
 start_time = datetime.now()
# 此处为业务逻辑代码
 print_cost(start_time)

发表评论

您的电子邮箱地址不会被公开。

Shopping Cart