首页 > 编程语言 >#yyds干货盘点#【愚公系列】2023年02月 .NET/C#知识点-程序运行计时的总结

#yyds干货盘点#【愚公系列】2023年02月 .NET/C#知识点-程序运行计时的总结

时间:2023-02-27 20:05:48浏览次数:32  
标签:知识点 Console 程序运行 yyds startTimestamp DateTime var Stopwatch ValueStopwatch

前言

在分析一个程序算法时间复杂度时,可以使用统计程序或程序片段的计算时间有助于理解程序性质,许多语言或系统都提供了内部计时功能。

下面主要是讲解C#中的计时方式:

  • Stopwatch
  • DateTime.Now
  • ValueStopwatch

一、程序运行计时的总结

1.Stopwatch

Stopwatch 一般用来测量代码运行消耗时间,以便获取更多代码运行性能上的数据。运行前先要调用 Start 函数来开始计时,结束时需要用到 Stop 函数停止计时,中间则可以插入需要监测的代码。如果有需要也还可以通过 Reset 或者 Restart 函数来重置计时器再开始下一次计时。

using System.Diagnostics;

Stopwatch sw = new Stopwatch();
sw.Start();
Thread.Sleep(999);
sw.Stop();
Console.WriteLine($"程序耗时:{sw.ElapsedMilliseconds}ms.");

Console.ReadKey();

在这里插入图片描述

2.DateTime.Now

DateTime是一个包含日期、时间的类型,此类型通过ToString()转换为字符串时,可根据传入给Tostring()的参数转换为多种字符串格式。

DateTime.Now主要是获取当前时间,所以也可以用于计算程序的执行时间

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

在这里插入图片描述

3.ValueStopwatch

ValueStopwatch主要是.NET Core才出现的,ValueStopwatch 的结构体是为了减少使用 Stopwatch 带来的内存分配从而提高性能,本质还是Stopwatch。

using System.Diagnostics;

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);
    }
}


在这里插入图片描述

标签:知识点,Console,程序运行,yyds,startTimestamp,DateTime,var,Stopwatch,ValueStopwatch
From: https://blog.51cto.com/u_15437432/6087014

相关文章