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);
            }
        }
    }
}
相关推荐
xlxxy_11 小时前
外部系统调用SAP接口遇到的一些报错
开发语言·数据库·sap·abap
八角.。11 小时前
方法参数与Debug按键
java·开发语言·jvm
郝亚军12 小时前
FE1.1S-BQFN24BT可以指定IP端口吗?
开发语言·php
阿里嘎多学长12 小时前
2026-08-04 GitHub 热点项目精选
开发语言·程序员·github·代码托管
晴天1612 小时前
Rust 快速入门 (从 JavaScript 开发者视角)-Day09
开发语言·javascript·rust
步行cgn12 小时前
carList.forEach(System.out::println)
java·开发语言·mybatis
进击的程序猿~13 小时前
Go 内存分配与垃圾回收源码深度学习手册
开发语言·后端·golang
geovindu13 小时前
go:Bit Operation Algorithm
开发语言·后端·算法·golang·位运算法
并不喜欢吃鱼14 小时前
从零开始 C++------ 十六.深度拆解 C++ 智能指针:unique_ptr/shared_ptr/weak_ptr 底层模拟、内存泄漏根治
开发语言·c++
CTuMei14 小时前
Free-Claude-Code 实战效果与能力边界全景展示
开发语言