You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python绘制函数时间效率图?解决耗时测量为0的问题

解决短耗时函数的计时与绘图异常问题

问题根源

三个函数的复杂度差异极大(O(1)、O(n)、O(n²)),但单个调用耗时远低于time.time()的精度阈值,导致多数时间差计算结果为0,无法反映真实性能差异,进而让绘图效果异常。

具体解决方案

1. 切换高精度计时工具

替换time.time()为time.perf_counter(),该函数专门针对短时间间隔测量优化,精度远高于time.time()。

2. 重复调用取平均

对耗时极短的函数,通过重复执行多次后计算单次平均耗时,避免出现0值。修改你的measure_time函数:

import time
import numpy as np
import pandas as pd
import seaborn as sns

def measure_time(n, func, repeat=1000):
    times_list = []
    for _ in range(1, n):
        start = time.perf_counter()
        # 重复执行func多次
        for _ in range(repeat):
            func(n)
        end = time.perf_counter()
        # 计算单次调用的平均耗时
        single_time = (end - start) / repeat
        times_list.append(single_time)
    return times_list

3. 针对不同函数设置差异化重复次数

由于三个函数的复杂度天差地别,统一重复次数会导致要么快函数测量不准,要么慢函数耗时过长,建议单独配置:

N = 1000
# sum_all_1是O(1),重复10000次保证测量精度
first_function_times = measure_time(N, sum_all_1, repeat=10000)
# sum_all_2是O(n),重复100次即可
second_function_times = measure_time(N, sum_all_2, repeat=100)
# sum_all_3是O(n²),单次调用耗时足够长,重复1次
third_function_times = measure_time(N, sum_all_3, repeat=1)

4. 优化绘图逻辑

原始数据噪声大,直接用散点图效果差,建议先平滑数据再绘图,或者转换为长表用箱线图对比分布:

# 构建DataFrame
values = np.array([first_function_times, second_function_times, third_function_times]).reshape(-1,3)
df_times = pd.DataFrame(data=values, index=range(1,N), columns=['first', 'second','third'])

# 方法1:滚动均值平滑后绘制折线图
df_times['first_smooth'] = df_times['first'].rolling(window=10).mean()
df_times['second_smooth'] = df_times['second'].rolling(window=10).mean()
df_times['third_smooth'] = df_times['third'].rolling(window=10).mean()
sns.lineplot(data=df_times[['first_smooth', 'second_smooth', 'third_smooth']])

# 方法2:转换为长表绘制箱线图,展示耗时分布
df_melted = df_times.melt(var_name='function', value_name='time')
sns.boxplot(x='function', y='time', data=df_melted)

内容的提问来源于stack exchange,提问作者yosef cohen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 07:10:12