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

        前例中有示例。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/639514.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

php no input file specified

一、修改 .user.ini 文件 内容 open_basedir/wab/led-sportslight.com/:/tmp/ led-sportslight.com是项目根目录位置 改好后保存并清空缓存硬刷新网站就行了 二、mkdir(): Permission denied /core/library/think/cache/driver/File.php 第 84 行左右 mkdir(): Permission de…

2024最新最全【网络安全面试题含答案】(非常详细),零基础入门到精通

防范常见的 Web 攻击 什么是SQL注入攻击 攻击者在HTTP请求中注入恶意的SQL代码&#xff0c;服务器使用参数构建数据库SQL命令时&#xff0c;恶意SQL被一起构造&#xff0c;并在数据库中执行。 用户登录&#xff0c;输入用户名 lianggzone&#xff0c;密码 ‘ or ‘1’’1 &a…

力扣刷题第八天 最大交换

给定一个非负整数&#xff0c;你至多可以交换一次数字中的任意两位。返回你能得到的最大值。 示例 1 : 输入: 2736 输出: 7236 解释: 交换数字2和数字7。示例 2 : 输入: 9973 输出: 9973 解释: 不需要交换。注意: 给定数字的范围是 [0, 10^8] 方法一&#xff1a;直接遍历 由于对…

使用 OpenCV 添加(混合)两个图像

目标 在本教程中&#xff0c;您将学习&#xff1a; 什么是线性混合以及为什么它有用;如何使用 addWeighted&#xff08;&#xff09; 添加两个图像 理论 注意 下面的解释属于Richard Szeliski的《计算机视觉&#xff1a;算法和应用》一书 从我们之前的教程中&#xff0c;…

LabVIEW扫描探针显微镜系统开发

在纳米技术对高精度材料特性测量的需求日益增长。介绍了基于LabVIEW开发的扫描探针显微镜&#xff08;SPM&#xff09;系统。该系统不仅可以高效地测量材料的热物性&#xff0c;还能在纳米尺度上探究热电性质&#xff0c;为材料研究提供了强大的工具。 系统基于扫描探针显微技…

(2)(2.1) Andruav Android Cellular(二)

文章目录 前言 5 Andruav Web Client 6 Andruav Telemetry 7 Andruav高级功能 8 将Andruav与SITL配合使用 9 FAQ 10 术语表 前言 Andruav 是一个基于安卓的互联系统&#xff0c;它将安卓手机作为公司计算机&#xff0c;为你的无人机和遥控车增添先进功能。 5 Andruav W…

数学建模--PageRank算法的Python实现

文章目录 1. P a g e R a n k PageRank PageRank算法背景2. P a g e R a n k PageRank PageRank算法基础2.1. P a g e R a n k PageRank PageRank问题描述2.2.有向图模型2.3.随机游走模型 3. P a g e R a n k PageRank PageRank算法定义3.1. P a g e R a n k PageRank PageRank…

GD32接收不定长数据包

接收不定长数据 Cubemx生成代码过程忽略 首先在main函数中创建接收缓存区 并在main.h中定义 接下来就是重写串口的中断函数中的内容&#xff0c;把原有内容注释掉 main中创建一个记录接收数据长度的变量和标志位 然后再在主函数中添加一个验证代码&#xff0c;这样MCU收到数据…

Cesium叠加超图二维服务、三维场景模型

前言 Cesium作为开源的库要加超图的服务则需要适配层去桥接超图与Cesium的数据格式。这个工作iClient系列已经做好&#xff0c;相比用过超图二维的道友们可以理解&#xff1a;要用Openlayer加载超图二维&#xff0c;那就用iClient for Openlayer库去加载&#xff1b;同样的要用…

el-table导出表格文件

先写一个download公共的方法 download(file) {const blob fileconst blobURL window.URL ? window.URL.createObjectURL(blob) : window.webkitURL.createObjectURL(blob)const a document.createElement(a)a.download 故障的报表.xlsxa.href blobURLdocument.body.appen…

Git与GitHub零基础教学

大家好&#xff0c;我是星恒&#xff0c;这个帖子给大家分享的是git和github的全套教程&#xff0c;包含github初始&#xff0c;git常用命令以及基本使用&#xff0c;git的ssh链接github&#xff0c;github使用token登录&#xff0c;github和idea的配合&#xff0c;一些平时常用…

Flink编程——基础环境搭建

基础环境搭建 文章目录 基础环境搭建准备环境搭建源码环境搭建克隆代码编译导入IDEA 集群环境搭建本地模式安装步骤 1&#xff1a;下载步骤 2&#xff1a;启动集群步骤 3&#xff1a;提交作业&#xff08;Job&#xff09;步骤 4&#xff1a;停止集群 总结 准备环境搭建 我们先…

我们需要练习关爱自己,让自己松弛下来,而练习的方式就是慈心,祝福自己也祝福他人

非常正确&#xff01;关爱自己是维持身心健康的关键之一。通过慈心和祝福的方式&#xff0c;我们可以培养更积极、更宽容的心态&#xff0c;提升生活质量。以下是一些建议&#xff0c;帮助你在日常生活中练习关爱自己&#xff1a; 自我体谅&#xff1a; 对待自己要像对待朋友一…

国内SAP实施公司大盘点

随着企业数字化转型的加速推进&#xff0c;SAP作为全球有名的企业软件解决方案提供商&#xff0c;受到了越来越多企业的青睐。然而&#xff0c;要充分发挥SAP软件的潜力&#xff0c;企业需要依赖专业的SAP实施公司来提供技术支持和咨询服务。在国内&#xff0c;有许多优秀的SAP…

Spring ApplicationContext

ApplicationContext 在 Spring 中代表着一个高级的 IoC 容器&#xff0c;负责实例化、配置和组装对象。ApplicationContext 接口扩展自 BeanFactory 接口&#xff0c;添加了更多的企业级功能&#xff0c;比如更容易的国际化、事件传播、资源加载等。 ApplicationContext 接口关…

web3d-three.js场景设计器-天空包围盒-TWEEN.js

THREE.JS 实现场景天空包围盒&#xff0c;为了让场景背景更具体&#xff0c;而不是呆板的纯色&#xff0c;可以给厂家添加围绕的包围盒。 这里使用球体来实现&#xff0c;球体中央则是场景给球体添加天空的渐变色加入场景 代码如下 function createSky( hemiLight) { const …

学习笔记——克里金插值

有一篇大神的文章写得非常的具体&#xff0c; https://xg1990.com/blog/archives/222 下面写下一些学习笔记&#xff1a; 1、关于克里金插值的基本原理 克里金插值来源于地理学&#xff0c;它的前提是地理学第一定律&#xff1a;所有事物都与其他事务相关&#xff0c;但是近…

应用层—HTTP详解(抓包工具、报文格式、构造http等……)

文章目录 HTTP1. 抓包工具的使用1.1 配置信息1.2 观察数据 2. 分析 https 抓包结果3. HTTP请求详解3.1 认识 URL3.1.1 URL 基本格式3.1.2 查询字符串 (query string)3.1.3 关于 URL Encode 3.2 认识 http 方法3.2.1 [经典问题] Get 和 Post 主要的区别是什么&#xff1f;&#…

Java多线程并发篇----第二十九篇

系列文章目录 文章目录 系列文章目录前言一、什么是不可变对象,它对写并发应用有什么帮助二、Java 中用到的线程调度算法是什么?三、什么是线程组,为什么在 Java 中不推荐使用?前言 前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点…

美易官方《美国股市在全球金融市场中的地位举足轻重》

美国股市在全球金融市场中的地位举足轻重&#xff0c;吸引了众多顶尖投资高手和机构竞相角逐。作为全球最大的股票市场之一&#xff0c;美国股市以其独特的魅力和优势&#xff0c;成为了全球投资者瞩目的焦点。 首先&#xff0c;美国股市的规模巨大&#xff0c;流动性充裕&…