QQ登录

只需要一步,快速开始

APP扫码登录

只需要一步,快速开始

查看: 2398|回复: 0

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

[复制链接]

等级头衔

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

丰功伟绩

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

联系方式
发表于 2022-10-19 09:53:45 | 显示全部楼层 |阅读模式
概述
9 f, R8 R9 L* C. U4 B( X6 S       计算一段程序的耗时是我们在编程中很常见的用法,那这节内容就通过实例的方式来演示几种常用的统计耗时的方法.
( B9 _. Y% o3 f方法一:stopwatch
% l3 b: k+ O/ o
  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.: G; {( V, q5 |2 x9 n9 a6 v
运行结果:
( O2 @2 V7 s6 n( Q/ K  Q0 M' q程序耗时:1012ms.
, _( ]4 J( p' |( m7 r# X5 z方法二:DateTime.Now+ c$ K! X, r* M! `8 k& S/ [! 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();
        }
运行结果:
! l+ x- k9 `/ P3 A. I* j3 c0 f程序耗时:1012.2267ms.
* O1 K& w: ~: n方法三:ValueStopwatch
" x: @4 O# x' l& N用法举例如下:: T& u" Y- I2 S2 z$ \
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);
        }
    }
}
运行结果:' e, u" I# [! Q/ A
程序耗时:1008.0426ms.
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

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

GMT+8, 2025-6-8 01:20

Powered by paopaomj X3.5 © 2016-2025 sitemap

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