QQ登录

只需要一步,快速开始

APP扫码登录

只需要一步,快速开始

手机号码,快捷登录

手机号码,快捷登录

查看: 2267|回复: 0

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

[复制链接]

等级头衔

积分成就    金币 : 2857
   泡泡 : 1516
   精华 : 6
   在线时间 : 1317 小时
   最后登录 : 2025-4-23

丰功伟绩

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

联系方式
发表于 2022-10-19 09:53:45 | 显示全部楼层 |阅读模式
概述" ]1 K: b- y$ ]# Y; K' }# u0 x
       计算一段程序的耗时是我们在编程中很常见的用法,那这节内容就通过实例的方式来演示几种常用的统计耗时的方法.; h( q- J5 G1 E+ y3 ^
方法一:stopwatch
5 T' M( f# I9 w" X  K7 i
  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.
/ ]: r( u+ _  H) t  N8 B. ], X运行结果:; }; x. V3 ?6 U5 |- C$ u5 w; e
程序耗时:1012ms.
% a$ \& A# \* q' Y& p% f方法二:DateTime.Now! V" `3 e+ ?5 E) w: c! \
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();
        }
运行结果:- n& D; A$ B0 _  s! W2 q! }
程序耗时:1012.2267ms.& x9 W9 k- D+ d3 y- M' ^
方法三:ValueStopwatch
. Y4 ^4 u, N: d6 B用法举例如下:$ q; R( b# _8 o1 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);
        }
    }
}
运行结果:  C3 n5 z+ @/ K. U5 z) E
程序耗时:1008.0426ms.
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

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

GMT+8, 2025-4-25 03:23

Powered by paopaomj X3.5 © 2016-2025 sitemap

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