QQ登录

只需要一步,快速开始

APP扫码登录

只需要一步,快速开始

查看: 2498|回复: 0

[C#/.NET] C# 计算耗时的三种方法

[复制链接]

等级头衔

积分成就    金币 : 2861
   泡泡 : 1516
   精华 : 6
   在线时间 : 1320 小时
   最后登录 : 2025-6-27

丰功伟绩

优秀达人突出贡献荣誉管理论坛元老活跃会员

联系方式
发表于 2022-10-19 09:53:45 | 显示全部楼层 |阅读模式
概述
9 m9 _4 G; s" N$ K; q/ \: z/ {       计算一段程序的耗时是我们在编程中很常见的用法,那这节内容就通过实例的方式来演示几种常用的统计耗时的方法.
- z; ^: p3 @/ Y  l9 Z5 n方法一:stopwatch. g; v. q2 I& Y# P$ [
  static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            Thread.Sleep(999);
            sw.Stop();
            Console.WriteLine($"程序耗时:{sw.ElapsedMilliseconds}ms.");

            Console.ReadKey();
        }
      最常用的计算耗时的就是使用Stopwatch,使用的时候需要引用命名空间:System.Diagnostics.
' [" v$ e! S" c+ m0 E( l运行结果:
& {2 d4 Y1 e% s1 Q: _; I! }程序耗时:1012ms.
8 f% z5 m' O0 Q# C9 o方法二:DateTime.Now; x$ y" b- J$ X# U' y/ ~
static void Main(string[] args)
        {
            //Stopwatch sw = new Stopwatch();
            //sw.Start();
            //Thread.Sleep(999);
            //sw.Stop();
            //Console.WriteLine($"程序耗时:{sw.ElapsedMilliseconds}ms.");

            var start = DateTime.Now;
            Thread.Sleep(999);
            var stop = DateTime.Now;
            Console.WriteLine($"程序耗时:{(stop - start).TotalMilliseconds}ms.");
            Console.ReadKey();
        }
运行结果:
0 A% U: a: T2 Q; O程序耗时:1012.2267ms.
- j8 M) Q" P9 N方法三:ValueStopwatch+ i8 I8 I8 O2 S$ O
用法举例如下:, A- [7 g+ |' u" w; `0 \- r, {
using System;
using System.Diagnostics;
using System.Threading;

namespace ConsoleApp27
{
    class Program
    { 
        static void Main(string[] args)
        {
            //Stopwatch sw = new Stopwatch();
            //sw.Start();
            //Thread.Sleep(999);
            //sw.Stop();
            //Console.WriteLine($"程序耗时:{sw.ElapsedMilliseconds}ms.");

            //var start = DateTime.Now;
            //Thread.Sleep(999);
            //var stop = DateTime.Now;
            //Console.WriteLine($"程序耗时:{(stop - start).TotalMilliseconds}ms.");

            var watch = ValueStopwatch.StartNew();
            Thread.Sleep(999);
            Console.WriteLine($"程序耗时:{watch.GetElapsedTime().TotalMilliseconds}ms.");
            Console.ReadKey();
        }
    }

    internal struct ValueStopwatch
    {
        private static readonly double TimestampToTicks = TimeSpan.TicksPerSecond / (double)Stopwatch.Frequency;

        private readonly long _startTimestamp;

        public bool IsActive => _startTimestamp != 0;

        private ValueStopwatch(long startTimestamp)
        {
            _startTimestamp = startTimestamp;
        }

        public static ValueStopwatch StartNew() => new ValueStopwatch(Stopwatch.GetTimestamp());

        public TimeSpan GetElapsedTime()
        {
            // Start timestamp can't be zero in an initialized ValueStopwatch. It would have to be literally the first thing executed when the machine boots to be 0.
            // So it being 0 is a clear indication of default(ValueStopwatch)
            if (!IsActive)
            {
                throw new InvalidOperationException("An uninitialized, or 'default', ValueStopwatch cannot be used to get elapsed time.");
            }

            var end = Stopwatch.GetTimestamp();
            var timestampDelta = end - _startTimestamp;
            var ticks = (long)(TimestampToTicks * timestampDelta);
            return new TimeSpan(ticks);
        }
    }
}
运行结果:( D. c9 D' t( q5 i( k
程序耗时:1008.0426ms.
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|小黑屋|paopaomj.COM ( 渝ICP备18007172号|渝公网安备50010502503914号 )

GMT+8, 2025-6-28 09:45

Powered by paopaomj X3.5 © 2016-2025 sitemap

快速回复 返回顶部 返回列表