QQ登录

只需要一步,快速开始

APP扫码登录

只需要一步,快速开始

手机号码,快捷登录

手机号码,快捷登录

查看: 1996|回复: 0

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

[复制链接]

等级头衔

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

丰功伟绩

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

联系方式
发表于 2022-10-19 09:53:45 | 显示全部楼层 |阅读模式
概述
0 x5 Y/ `1 U" @3 v+ G* ]% M: Z$ `       计算一段程序的耗时是我们在编程中很常见的用法,那这节内容就通过实例的方式来演示几种常用的统计耗时的方法.7 D. [6 e. m! K% ~  K
方法一:stopwatch& ^  A9 n1 M7 f0 z9 Z
  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.# B. |0 w, g# L6 b
运行结果:
" k) ~- t4 y4 a- H程序耗时:1012ms.! k" G6 X. }$ Q) f/ c
方法二:DateTime.Now$ k1 \3 |; N, D+ c3 Y& _# t
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();
        }
运行结果:; Z; H( {% ^3 D' H% z5 `
程序耗时:1012.2267ms.
& m; b$ G' [& ^3 }7 h& b$ E# Z: x方法三:ValueStopwatch
& V6 a3 Z( q- M0 g用法举例如下:% j" f( U/ n- }/ i# b
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);
        }
    }
}
运行结果:
1 K- H4 B) w% }' Z, ?. N程序耗时:1008.0426ms.
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

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

GMT+8, 2025-2-21 03:09

Powered by paopaomj X3.5 © 2016-2025 sitemap

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