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);
            }
        }
    }
}
相关推荐
唐青枫8 小时前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech17 小时前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf2 天前
C#摸鱼实录——IoC与DI案例详解
c#
咕白m6252 天前
使用 C# 在 Excel 中应用多种字体样式
后端·c#
Artech3 天前
[MAF预定义的AIContextProvider-02]AgentSkillsProvider——将Agent Skills引入MAF
ai·c#·agent·agent skills·maf
LDR0063 天前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
雪碧聊技术3 天前
Tree.js是什么?一文讲透
开发语言·javascript·ecmascript
码云数智-园园3 天前
C++20 Modules 模块详解
java·开发语言·spring
swordbob3 天前
NIO的channel中什么是 fd(File Descriptor,文件描述符)
java·开发语言·nio
源分享3 天前
Java线程同步的多种实现方法(非常详细)
java·开发语言·jvm