C#基础:使用Stopwatch计时及统计特定方法的执行效率

一、基础操作

// 创建一个 Stopwatch 实例,用于监控代码的运行时间
System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();

// 开始计时
stopwatch.Start(); // 开始监视代码运行时间

// 获取从计时器开始到现在的经过时间
TimeSpan timespan = stopwatch.Elapsed;

// 重置且重启计时器,此时先前的计时结果会被清除
stopwatch.Restart(); 

// 计时器运行?=>停止计时
if (stopwatch.IsRunning)
{
    stopwatch.Stop(); 
}

二、统计方法用时

using System.Diagnostics;

class TimeCalculator//视情况加public修饰符,下同
{
    private readonly List<TimeMessage> calculations = new List<TimeMessage>();//初始化,后面实例方法需要用到
    private readonly Stopwatch stopwatch = new Stopwatch();

    public void Start()
    {
        stopwatch.Start();//开始计时
    }

    public void Stop(string name)
    {
        stopwatch.Stop();//结束计时

        var calculation = new TimeMessage
        {
            Name = name,
            Time = stopwatch.Elapsed
        };

        calculations.Add(calculation);//记录数据,存放到时间信息列表

        stopwatch.Reset();//重置计时器
    }

    public void PrintResults()//打印时间信息列表
    {
        foreach (var calculation in calculations)
        {
            Console.WriteLine($"{calculation.Name}: {calculation.Time}");
        }
    }

    public List<TimeMessage> ReturnResults()//返回时间信息列表
    {
        return calculations;
    }
}

class TimeMessage
{
    public string Name { get; set; }
    public TimeSpan Time { get; set; }
}

class Test
{
    static void Method1()
    {
        for (int i = 0; i < 100000; i++)
        {
            var a = i;
        }
    }

    static void Method2()
    {
        for (int i = 0; i < 300000; i++)
        {
            var b = i;
        }
    }

    static int Main(string[] args)
    {
        var calculator = new TimeCalculator();//实例化一个类(为这个类创建对象)

        calculator.Start();//对象调用方法:开始计时
        Method1();
        calculator.Stop("Method1");//对象调用方法:结束计时并且登记名字

        calculator.Start();
        Method2();
        calculator.Stop("Method2");

        calculator.PrintResults();//打印计时结论
        var calculresult = calculator.ReturnResults();//获取计时结论列表

        return 0;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值