Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python 运行时间

作者:看不见相思意   发布日期:2025-03-28   浏览:29

import time

def measure_runtime(func):
    start_time = time.time()  # 记录函数开始执行的时间
    func()  # 执行传入的函数
    end_time = time.time()  # 记录函数结束执行的时间
    print(f"运行时间: {end_time - start_time} 秒")  # 输出运行时间

# 示例函数
def example_function():
    time.sleep(2)  # 模拟一个耗时操作,休眠2秒

# 调用测量运行时间的函数
measure_runtime(example_function)

解释说明:

  1. 导入模块:我们使用 time 模块来获取当前时间。
  2. 定义 measure_runtime 函数:该函数接受一个函数对象 func 作为参数。它记录下 func 开始和结束的时间,并计算出运行时间。
  3. 示例函数 example_function:这个函数模拟了一个耗时操作(例如休眠2秒)。
  4. 调用 measure_runtime:我们将 example_function 传递给 measure_runtime 来测量它的运行时间。

通过这种方式,你可以轻松测量任何 Python 函数的运行时间。

上一篇:python爬虫程序

下一篇:python入口函数

大家都在看

python时间格式

python ord和chr

python中的yield

python list.pop

python的for i in range

npm config set python

python代码简单

python读取文件夹

python中turtle

python 输出时间

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站