QQ登录

只需要一步,快速开始

APP扫码登录

只需要一步,快速开始

查看: 2437|回复: 0

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

[复制链接]

等级头衔

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

丰功伟绩

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

联系方式
发表于 2022-10-19 09:53:45 | 显示全部楼层 |阅读模式
概述& ^1 ^; k  [+ k" x# R
       计算一段程序的耗时是我们在编程中很常见的用法,那这节内容就通过实例的方式来演示几种常用的统计耗时的方法., y5 ?. |6 O0 t! m  I6 C+ E
方法一:stopwatch8 ?  T0 s- k' i7 E4 p" t  ~
  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.
3 q' ]! B0 J) Y% v% I运行结果:3 _/ F* [" z& M( X3 P9 o. `7 `
程序耗时:1012ms.( {& B% x& z' Y8 i# s: J7 v
方法二:DateTime.Now: i  e5 W6 i/ d1 h/ V
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();
        }
运行结果:
8 U* f. K3 t( Z2 {程序耗时:1012.2267ms.
0 g+ n2 d5 v, W( ^, B! t0 s方法三:ValueStopwatch
; I8 j- e/ y) i1 k, v/ ~6 [用法举例如下:' \! t, U  X5 J  [: g
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);
        }
    }
}
运行结果:
0 }' T3 k8 ~: c$ j+ ]/ I" i程序耗时:1008.0426ms.
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

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

GMT+8, 2025-6-17 16:10

Powered by paopaomj X3.5 © 2016-2025 sitemap

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