C# 用于准确地测量运行时间的Stopwatch中.Start 方法和Stopwatch.Stop 方法

本文主要是介绍C# 用于准确地测量运行时间的Stopwatch中.Start 方法和Stopwatch.Stop 方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

 

一、Stopwatch 类

        提供一组方法和属性,可用于准确地测量运行时间。

public class Stopwatch

        使用 Stopwatch 类来确定应用程序的执行时间。

// 使用 Stopwatch 类来确定应用程序的执行时间
using System.Diagnostics;
class Program
{static void Main(string[] args){ArgumentNullException.ThrowIfNull(args);Stopwatch stopWatch = new();stopWatch.Start();Thread.Sleep(10000);stopWatch.Stop();// Get the elapsed time as a TimeSpan value.TimeSpan ts = stopWatch.Elapsed;// Format and display the TimeSpan value.string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",ts.Hours, ts.Minutes, ts.Seconds,ts.Milliseconds / 10);Console.WriteLine("RunTime " + elapsedTime);}
}
//运行结果:
/*
RunTime 00:00:10.01*/
// 使用 Stopwatch 类来计算性能数据。
using System.Diagnostics;namespace StopWatchSample
{class OperationsTimer{public static void Main(string[] args){ArgumentNullException.ThrowIfNull(args);DisplayTimerProperties();Console.WriteLine();Console.WriteLine("Press the Enter key to begin:");Console.ReadLine();Console.WriteLine();TimeOperations();}public static void DisplayTimerProperties(){// Display the timer frequency and resolution.if (Stopwatch.IsHighResolution){Console.WriteLine("Operations timed using the system's high-resolution performance counter.");}else{Console.WriteLine("Operations timed using the DateTime class.");}long frequency = Stopwatch.Frequency;Console.WriteLine("  Timer frequency in ticks per second = {0}",frequency);long nanosecPerTick = (1000L * 1000L * 1000L) / frequency;Console.WriteLine("  Timer is accurate within {0} nanoseconds",nanosecPerTick);}private static void TimeOperations(){long nanosecPerTick = (1000L * 1000L * 1000L) / Stopwatch.Frequency;const long numIterations = 10000;// Define the operation title names.string[] operationNames = {"Operation: Int32.Parse(\"0\")","Operation: Int32.TryParse(\"0\")","Operation: Int32.Parse(\"a\")","Operation: Int32.TryParse(\"a\")"};// Time four different implementations for parsing// an integer from a string.for (int operation = 0; operation <= 3; operation++){// Define variables for operation statistics.long numTicks = 0;long numRollovers = 0;long maxTicks = 0;long minTicks = long.MaxValue;int indexFastest = -1;int indexSlowest = -1;Stopwatch time10kOperations = Stopwatch.StartNew();// Run the current operation 10001 times.// The first execution time will be tossed// out, since it can skew the average time.for (int i = 0; i <= numIterations; i++){long ticksThisTime = 0;int inputNum;Stopwatch timePerParse;switch (operation){case 0:// Parse a valid integer using// a try-catch statement.// Start a new stopwatch timer.timePerParse = Stopwatch.StartNew();try{inputNum = int.Parse("0");}catch (FormatException){inputNum = 0;}// Stop the timer, and save the// elapsed ticks for the operation.timePerParse.Stop();ticksThisTime = timePerParse.ElapsedTicks;break;case 1:// Parse a valid integer using// the TryParse statement.// Start a new stopwatch timer.timePerParse = Stopwatch.StartNew();if (!int.TryParse("0", out inputNum)){inputNum = 0;}// Stop the timer, and save the// elapsed ticks for the operation.timePerParse.Stop();ticksThisTime = timePerParse.ElapsedTicks;break;case 2:// Parse an invalid value using// a try-catch statement.// Start a new stopwatch timer.timePerParse = Stopwatch.StartNew();try{inputNum = int.Parse("a");}catch (FormatException){inputNum = 0;}// Stop the timer, and save the// elapsed ticks for the operation.timePerParse.Stop();ticksThisTime = timePerParse.ElapsedTicks;break;case 3:// Parse an invalid value using// the TryParse statement.// Start a new stopwatch timer.timePerParse = Stopwatch.StartNew();if (!int.TryParse("a", out inputNum)){inputNum = 0;}// Stop the timer, and save the// elapsed ticks for the operation.timePerParse.Stop();ticksThisTime = timePerParse.ElapsedTicks;break;default:break;}// Skip over the time for the first operation,// just in case it caused a one-time// performance hit.if (i == 0){time10kOperations.Reset();time10kOperations.Start();}else{// Update operation statistics// for iterations 1-10000.if (maxTicks < ticksThisTime){indexSlowest = i;maxTicks = ticksThisTime;}if (minTicks > ticksThisTime){indexFastest = i;minTicks = ticksThisTime;}numTicks += ticksThisTime;if (numTicks < ticksThisTime){// Keep track of rollovers.numRollovers++;}}}// Display the statistics for 10000 iterations.time10kOperations.Stop();long milliSec = time10kOperations.ElapsedMilliseconds;Console.WriteLine();Console.WriteLine("{0} Summary:", operationNames[operation]);Console.WriteLine("  Slowest time:  #{0}/{1} = {2} ticks",indexSlowest, numIterations, maxTicks);Console.WriteLine("  Fastest time:  #{0}/{1} = {2} ticks",indexFastest, numIterations, minTicks);Console.WriteLine("  Average time:  {0} ticks = {1} nanoseconds",numTicks / numIterations,(numTicks * nanosecPerTick) / numIterations);Console.WriteLine("  Total time looping through {0} operations: {1} milliseconds",numIterations, milliSec);}}}
}
//运行结果:
/*
Operations timed using the system's high-resolution performance counter.Timer frequency in ticks per second = 10000000Timer is accurate within 100 nanoseconds*/

1.Stopwatch.Start 方法

        开始或继续测量某个时间间隔的运行时间。

        前例中有示例。 

public void Start ();

2.Stopwatch.Stop 方法

        停止测量某个时间间隔的运行时间。

public void Stop ();

        前例中有示例。

这篇关于C# 用于准确地测量运行时间的Stopwatch中.Start 方法和Stopwatch.Stop 方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/634394

相关文章

CentOS7增加Swap空间的两种方法

《CentOS7增加Swap空间的两种方法》当服务器物理内存不足时,增加Swap空间可以作为虚拟内存使用,帮助系统处理内存压力,本文给大家介绍了CentOS7增加Swap空间的两种方法:创建新的Swa... 目录在Centos 7上增加Swap空间的方法方法一:创建新的Swap文件(推荐)方法二:调整Sww

QT6中绘制UI的两种方法详解与示例代码

《QT6中绘制UI的两种方法详解与示例代码》Qt6提供了两种主要的UI绘制技术:​​QML(QtMeta-ObjectLanguage)​​和​​C++Widgets​​,这两种技术各有优势,适用于不... 目录一、QML 技术详解1.1 QML 简介1.2 QML 的核心概念1.3 QML 示例:简单按钮

基于C#实现MQTT通信实战

《基于C#实现MQTT通信实战》MQTT消息队列遥测传输,在物联网领域应用的很广泛,它是基于Publish/Subscribe模式,具有简单易用,支持QoS,传输效率高的特点,下面我们就来看看C#实现... 目录1、连接主机2、订阅消息3、发布消息MQTT(Message Queueing Telemetr

Python日期和时间完全指南与实战

《Python日期和时间完全指南与实战》在软件开发领域,‌日期时间处理‌是贯穿系统设计全生命周期的重要基础能力,本文将深入解析Python日期时间的‌七大核心模块‌,通过‌企业级代码案例‌揭示最佳实践... 目录一、背景与核心价值二、核心模块详解与实战2.1 datetime模块四剑客2.2 时区处理黄金法

Spring Boot项目打包和运行的操作方法

《SpringBoot项目打包和运行的操作方法》SpringBoot应用内嵌了Web服务器,所以基于SpringBoot开发的web应用也可以独立运行,无须部署到其他Web服务器中,下面以打包dem... 目录一、打包为JAR包并运行1.打包为可执行的 JAR 包2.运行 JAR 包二、打包为WAR包并运行

C#特性(Attributes)和反射(Reflection)详解

《C#特性(Attributes)和反射(Reflection)详解》:本文主要介绍C#特性(Attributes)和反射(Reflection),具有很好的参考价值,希望对大家有所帮助,如有错误... 目录特性特性的定义概念目的反射定义概念目的反射的主要功能包括使用反射的基本步骤特性和反射的关系总结特性

macOS Sequoia 15.5 发布: 改进邮件和屏幕使用时间功能

《macOSSequoia15.5发布:改进邮件和屏幕使用时间功能》经过常规Beta测试后,新的macOSSequoia15.5现已公开发布,但重要的新功能将被保留到WWDC和... MACOS Sequoia 15.5 正式发布!本次更新为 Mac 用户带来了一系列功能强化、错误修复和安全性提升,进一步增

Oracle 通过 ROWID 批量更新表的方法

《Oracle通过ROWID批量更新表的方法》在Oracle数据库中,使用ROWID进行批量更新是一种高效的更新方法,因为它直接定位到物理行位置,避免了通过索引查找的开销,下面给大家介绍Orac... 目录oracle 通过 ROWID 批量更新表ROWID 基本概念性能优化建议性能UoTrFPH优化建议注

Pandas进行周期与时间戳转换的方法

《Pandas进行周期与时间戳转换的方法》本教程将深入讲解如何在pandas中使用to_period()和to_timestamp()方法,完成时间戳与周期之间的转换,并结合实际应用场景展示这些方法的... 目录to_period() 时间戳转周期基本操作应用示例to_timestamp() 周期转时间戳基

在 PyQt 加载 UI 三种常见方法

《在PyQt加载UI三种常见方法》在PyQt中,加载UI文件通常指的是使用QtDesigner设计的.ui文件,并将其转换为Python代码,以便在PyQt应用程序中使用,这篇文章给大家介绍在... 目录方法一:使用 uic 模块动态加载 (不推荐用于大型项目)方法二:将 UI 文件编译为 python 模