C#---StopWatch类

老方法,想要全面了解和学习一个类必先看文档 微软文档

1.StopWatch

提供一组方法和属性,可用来测量运行时间。

1.1 属性和方法

属性:

方法:

1.2 使用

csharp 复制代码
using System.Diagnostics;

namespace Study04_反射专题
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");

            // 提供一组方法和属性,可用于准确地测量运行时间。
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Restart();
            Thread.Sleep(1000); // 模拟耗时操作
            Console.WriteLine(stopwatch.ElapsedMilliseconds);
            stopwatch.Restart();
            Console.WriteLine(stopwatch.ElapsedMilliseconds);

            Computer computer = new Computer();
            MeasureTimeHelper.Measure(null, () => computer.Add(1, 10000000), out long time);
            Console.WriteLine(string.Format("使用{0}ms",time));

            Console.ReadKey();
        }
    }


    public class Computer
    {
        public void Add(int a, int b)
        {
            int sum = 0;
            for (int i = a; i < b; i++)
            {
                sum += a;
            }
            Console.WriteLine(sum);
        }
    }


    public static class MeasureTimeHelper
    {
        public static void Measure(this object obj, Action action, out long time)
        {
            time = 0;
            try
            {
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Restart();
                action?.Invoke();
                stopwatch.Stop();
                time = stopwatch.ElapsedMilliseconds;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
        }
    }
}
相关推荐
阿珊和她的猫31 分钟前
v-scale-scree: 根据屏幕尺寸缩放内容
开发语言·前端·javascript
fouryears_234173 小时前
Flutter InheritedWidget 详解:从生命周期到数据流动的完整解析
开发语言·flutter·客户端·dart
lifallen5 小时前
Java Stream sort算子实现:SortedOps
java·开发语言
IT毕设实战小研5 小时前
基于Spring Boot 4s店车辆管理系统 租车管理系统 停车位管理系统 智慧车辆管理系统
java·开发语言·spring boot·后端·spring·毕业设计·课程设计
cui__OaO6 小时前
Linux软件编程--线程
linux·开发语言·线程·互斥锁·死锁·信号量·嵌入式学习
鱼鱼说测试7 小时前
Jenkins+Python自动化持续集成详细教程
开发语言·servlet·php
艾莉丝努力练剑7 小时前
【洛谷刷题】用C语言和C++做一些入门题,练习洛谷IDE模式:分支机构(一)
c语言·开发语言·数据结构·c++·学习·算法
一阵没来由的风7 小时前
拒绝造轮子(C#篇)ZLG CAN卡驱动封装应用
c#·can·封装·zlg·基础封装·轮子
CHEN5_027 小时前
【Java基础面试题】Java基础概念
java·开发语言