在C#中,可以使用Stopwatch类来计算方法的执行耗时。Stopwatch类提供了计时器功能,可以用来测量代码块的执行时间。以下是一个示例代码:

using System;
using System.Diagnostics;
using System.Threading;

class Program
{
    static void Main()
    {
        // 创建 Stopwatch 实例
        Stopwatch stopwatch = new Stopwatch();

        // 启动计时器
        stopwatch.Start();

        // 创建线程
        Thread thread = new Thread(TestMethod);

        // 启动线程
        thread.Start();

        // 等待线程执行完成
        thread.Join();

        // 停止计时器
        stopwatch.Stop();

        // 输出耗时
        Console.WriteLine("方法执行耗时: {0} 毫秒", stopwatch.ElapsedMilliseconds);
    }

    static void TestMethod()
    {
        // 模拟耗时操作
        Thread.Sleep(2000);
    }
}

在上述代码中,首先创建一个Stopwatch实例,并通过Start方法启动计时器。然后创建一个新的线程,并通过Start方法启动线程。在主线程中,通过Join方法等待线程执行完成。最后,通过Stop方法停止计时器,并通过ElapsedMilliseconds属性获取方法的执行耗时

C# 多线程下如何计算方法执行耗时

原文地址: http://www.cveoy.top/t/topic/i0Jh 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录