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

C#如何利用Stopwatch封装函数统计执行耗时?

封装任意方法调用的耗时统计方案

嘿,我刚好做过类似的需求!要实现用你的StopwatcherData类封装任意方法调用并统计执行时长,咱们可以借助C#的委托(Action/Func)结合泛型来实现,既能处理无返回值的方法,也能兼容有返回值的方法,完全贴合你的需求。

首先先把你给出的StopwatcherData类补全(看起来代码没写完):

public class StopwatcherData 
{ 
    public long Time { get; set; } 
    public string Message { get; set; } 

    public StopwatcherData(long time, string message) 
    { 
        Time = time; 
        Message = message; 
    } 
}

接下来咱们写核心的辅助类StopwatchHelper,用委托来接收任意方法:

using System.Diagnostics;

public static class StopwatchHelper
{
    // 处理无返回值的方法
    public static StopwatcherData Measure(Action action, string message)
    {
        var stopwatch = Stopwatch.StartNew();
        try
        {
            action.Invoke();
        }
        finally
        {
            stopwatch.Stop();
        }
        return new StopwatcherData(stopwatch.ElapsedMilliseconds, message);
    }

    // 处理有返回值的方法,用泛型适配任意返回类型
    public static (T Result, StopwatcherData WatchData) Measure<T>(Func<T> func, string message)
    {
        var stopwatch = Stopwatch.StartNew();
        T result = default;
        try
        {
            result = func.Invoke();
        }
        finally
        {
            stopwatch.Stop();
        }
        return (result, new StopwatcherData(stopwatch.ElapsedMilliseconds, message));
    }
}

使用示例

现在你就可以轻松封装任意方法调用了:

  1. 无返回值方法
// 假设你有一个要统计的方法
private void ProcessLargeData()
{
    // 模拟耗时操作
    Thread.Sleep(1000);
}

// 调用统计
var watchData = StopwatchHelper.Measure(ProcessLargeData, "处理大数据集耗时");
Console.WriteLine($"{watchData.Message}: {watchData.Time}ms");
  1. 有返回值方法
// 假设你有一个带返回值的方法
private int CalculateSum(int a, int b)
{
    // 模拟计算耗时
    Thread.Sleep(500);
    return a + b;
}

// 调用统计(用lambda表达式传递带参数的方法)
var (sumResult, sumWatchData) = StopwatchHelper.Measure(() => CalculateSum(10, 20), "计算两数之和耗时");
Console.WriteLine($"计算结果:{sumResult},{sumWatchData.Message}: {sumWatchData.Time}ms");

关键说明

  • 用try-finally确保Stopwatch一定会停止,避免方法抛出异常时统计失效
  • 泛型版本Measure<T>支持任意返回类型,同时返回方法结果和耗时数据,不用额外处理返回值的问题
  • 对于带参数的方法,用lambda表达式包装一下就能完美适配,非常灵活

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:03:29