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

相关文章

Pytest多环境切换的常见方法介绍

《Pytest多环境切换的常见方法介绍》Pytest作为自动化测试的主力框架,如何实现本地、测试、预发、生产环境的灵活切换,本文总结了通过pytest框架实现自由环境切换的几种方法,大家可以根据需要进... 目录1.pytest-base-url2.hooks函数3.yml和fixture结论你是否也遇到过

鸿蒙中Axios数据请求的封装和配置方法

《鸿蒙中Axios数据请求的封装和配置方法》:本文主要介绍鸿蒙中Axios数据请求的封装和配置方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1.配置权限 应用级权限和系统级权限2.配置网络请求的代码3.下载在Entry中 下载AxIOS4.封装Htt

Redis实现延迟任务的三种方法详解

《Redis实现延迟任务的三种方法详解》延迟任务(DelayedTask)是指在未来的某个时间点,执行相应的任务,本文为大家整理了三种常见的实现方法,感兴趣的小伙伴可以参考一下... 目录1.前言2.Redis如何实现延迟任务3.代码实现3.1. 过期键通知事件实现3.2. 使用ZSet实现延迟任务3.3

idea maven编译报错Java heap space的解决方法

《ideamaven编译报错Javaheapspace的解决方法》这篇文章主要为大家详细介绍了ideamaven编译报错Javaheapspace的相关解决方法,文中的示例代码讲解详细,感兴趣的... 目录1.增加 Maven 编译的堆内存2. 增加 IntelliJ IDEA 的堆内存3. 优化 Mave

Java String字符串的常用使用方法

《JavaString字符串的常用使用方法》String是JDK提供的一个类,是引用类型,并不是基本的数据类型,String用于字符串操作,在之前学习c语言的时候,对于一些字符串,会初始化字符数组表... 目录一、什么是String二、如何定义一个String1. 用双引号定义2. 通过构造函数定义三、St

golang获取当前时间、时间戳和时间字符串及它们之间的相互转换方法

《golang获取当前时间、时间戳和时间字符串及它们之间的相互转换方法》:本文主要介绍golang获取当前时间、时间戳和时间字符串及它们之间的相互转换,本文通过实例代码给大家介绍的非常详细,感兴趣... 目录1、获取当前时间2、获取当前时间戳3、获取当前时间的字符串格式4、它们之间的相互转化上篇文章给大家介

Spring Security方法级安全控制@PreAuthorize注解的灵活运用小结

《SpringSecurity方法级安全控制@PreAuthorize注解的灵活运用小结》本文将带着大家讲解@PreAuthorize注解的核心原理、SpEL表达式机制,并通过的示例代码演示如... 目录1. 前言2. @PreAuthorize 注解简介3. @PreAuthorize 核心原理解析拦截与

一文详解JavaScript中的fetch方法

《一文详解JavaScript中的fetch方法》fetch函数是一个用于在JavaScript中执行HTTP请求的现代API,它提供了一种更简洁、更强大的方式来处理网络请求,:本文主要介绍Jav... 目录前言什么是 fetch 方法基本语法简单的 GET 请求示例代码解释发送 POST 请求示例代码解释

Feign Client超时时间设置不生效的解决方法

《FeignClient超时时间设置不生效的解决方法》这篇文章主要为大家详细介绍了FeignClient超时时间设置不生效的原因与解决方法,具有一定的的参考价值,希望对大家有一定的帮助... 在使用Feign Client时,可以通过两种方式来设置超时时间:1.针对整个Feign Client设置超时时间

springboot+dubbo实现时间轮算法

《springboot+dubbo实现时间轮算法》时间轮是一种高效利用线程资源进行批量化调度的算法,本文主要介绍了springboot+dubbo实现时间轮算法,文中通过示例代码介绍的非常详细,对大家... 目录前言一、参数说明二、具体实现1、HashedwheelTimer2、createWheel3、n