在 Python 代码中添加计时功能的方法

在 Python 中测量算法运行时间,可以使用time模块或timeit模块。

方法一:使用time模块(基础版)

python

import time

def measure_time(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"函数 {func.__name__} 运行时间:{end_time - start_time:.4f} 秒")
        return result
    return wrapper

# 使用示例
@measure_time
def create_equipment_nodes_from_file(file_path):
    # 原有代码逻辑
    equipment_nodes = []
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            for line in file:
                parts = line.strip().split()
                if len(parts) == 3:
                    # 解析逻辑...
                    pass
    except Exception as e:
        print(f"Error: {e}")
    return equipment_nodes

# 调用函数
nodes = create_equipment_nodes_from_file("equipment_nodes.txt")

方法二:使用装饰器(进阶版)

python

import time
from functools import wraps

def timing_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        end = time.perf_counter()
        print(f"[{func.__name__}] 运行时间:{end - start:.6f} 秒")
        return result
    return wrapper

# 使用示例
@timing_decorator
def complex_algorithm():
    # 模拟耗时操作
    time.sleep(2)

complex_algorithm()  # 输出运行时间

方法三:使用timeit模块(高精度测量)

python

import timeit

def test_function():
    # 待测试的代码
    create_equipment_nodes_from_file("equipment_nodes.txt")

# 测量10次运行的平均时间
execution_time = timeit.timeit(test_function, number=10)
print(f"平均运行时间:{execution_time / 10:.6f} 秒")

如果原程序没有计时,可以对原程序做如下修改:

  1. 新增计时模块:在代码开头添加import time
  2. 开始计时:在main()函数最开始添加start_time = time.time()
  3. 结束计时:在main()函数所有逻辑执行完毕后添加end_time = time.time()
  4. 输出时间:在最后打印总执行时间,格式为 4 位小数
    print(f"\nTotal execution time: {end_time - start_time:.4f} seconds")  # 输出总时间

 

你可能感兴趣的:(python,前端,javascript)