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 分钟前
Python 对接 API:自动化拉取、清洗、入库一站式教程
开发语言·python·自动化
Omigeq14 分钟前
1.4 - 曲线生成轨迹优化算法(以BSpline和ReedsShepp为例) - Python运动规划库教程(Python Motion Planning)
开发语言·人工智能·python·算法·机器人
2301_8084143816 分钟前
自动化测试的实施
开发语言·python
波波00733 分钟前
写出稳定C#系统的关键:不可变性思想解析
开发语言·c#·wpf
willhuo1 小时前
基于Playwright的抖音网页自动化浏览器项目使用指南
爬虫·c#·.netcore·webview
dr_yingli1 小时前
fMRI(3-1)报告(个体化报告)生成器说明
开发语言·matlab
hrhcode1 小时前
【java工程师快速上手go】一.Go语言基础
java·开发语言·golang
飞Link1 小时前
【AI大模型实战】万字长文肝透大语言模型(LLM):从底层原理解析到企业级Python项目落地
开发语言·人工智能·python·语言模型·自然语言处理
妙蛙种子3111 小时前
【Java设计模式 | 创建者模式】 原型模式
java·开发语言·后端·设计模式·原型模式
LlNingyu1 小时前
Go 实现无锁环形队列:面向多生产者多消费者的高性能 MPMC 设计
开发语言·golang·队列·mpmc·数据通道