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);
            }
        }
    }
}
相关推荐
MyFreeIT3 分钟前
Python Windows Manual
开发语言·python
胖纸不争3 分钟前
EnergyStarZ:让 Windows 后台进程给前台让路的能效管理器(v1.2 发布)
windows·性能优化·c#·win32·ef core
kiracrimson14 分钟前
STL:List的使用和模拟实现
开发语言·c++·list
北冥you鱼1 小时前
Go 语言 GORM 使用 Preload:从关联查询到嵌套预加载的完整实践
开发语言·jvm·golang
dingzd951 小时前
TikTok账号登录态失效的Cookie字段排查路径
开发语言·php·跨境电商·营销策略
曹牧1 小时前
C#:The operation has timed out
开发语言·c#
He BianGu1 小时前
【WPF-Control教程】IOC 依赖注入
c#·wpf·wpf-control
你看我名字1 小时前
数眼智能 Search + Reader 实战:联网问答怎样避免“搜到了,却引用错了”
android·java·开发语言
小嘉丶学长1 小时前
Day13 · 列表与元组
linux·运维·服务器·开发语言·python
努力努力再努力wz2 小时前
【Lua入门系列】从 C++ 迭代器到 Lua 迭代器:一文深入理解 Lua 有状态以及无状态迭代器与泛型for、闭包、ipairs、pairs 和 next
开发语言·c++·lua