前言
在 c# 中,stopwatch 类是用于测量经过的时间的工具类,提供了高精度的计时功能。stopwatch 类位于 system.diagnostics 命名空间中。通常情况下,使用 stopwatch 的流程是创建一个 stopwatch 对象,然后调用 start 方法开始计时,执行需要测量时间的代码,最后调用 stop 方法停止计时,并通过 elapsed 属性获取经过的时间。
stopwatch 类中常用的方法包括
start():开始计时。
stop():停止计时。
reset():重置计时器。
restart():重启计时器。
elapsed:获取经过的时间(elapsed 属性返回一个 timespan 对象,表示自 stopwatch 实例开始计时以来经过的时间。你可以通过访问 elapsed 属性来获取经过的时间)
elapsedmilliseconds:回一个 long 值,表示自 stopwatch 实例开始计时以来经过的毫秒数。
elapsedticks:返回一个 long 值,表示自 stopwatch 实例开始计时以来经过的计时周期数。这个值通常用于更精确的时间测量。
使用示例
using system; using system.diagnostics; class program { static void main() { stopwatch stopwatch = new stopwatch(); stopwatch.start(); // 模拟耗时操作 for (int i = 0; i < 1000000; i++) { // do something } stopwatch.stop(); console.writeline($"经过的时间: {stopwatch.elapsed}"); } }
使用总结
通过使用 stopwatch
类,开发人员可以更准确地测量代码执行的时间,进行性能分析和优化,从而提升应用程序的性能表现。
知识补充
除了上文的内容,小编还为大家整理一些stopwatch类的其他应用,希望对大家有所帮助
c# stopwatch 实现程序精准计时
下面的示例演示如何使用stopwatch类来确定应用程序的执行时间。
using system; using system.diagnostics; using system.threading; class program { static void main(string[] args) { stopwatch stopwatch = new stopwatch(); // 开始 stopwatch.start(); // 程序执行 thread.sleep(10000); // 结束 stopwatch.stop(); // 获取作为 timespan 值的经过时间。 timespan ts = stopwatch.elapsed; // 格式化 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); } }
stopwatch还可以来计算性能数据,示例代码如下:
using system; using system.diagnostics; namespace stopwatchsample { class operationstimer { public static void main() { 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 = int64.maxvalue; int indexfastest = -1; int indexslowest = -1; long millisec = 0; 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 = int32.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 (!int32.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 = int32.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 (!int32.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(); 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); } } } }
stopwatch实现对程序运行的精确计时
demo
using system; using system.collections.generic; using system.diagnostics; using system.linq; using system.text; using system.threading; using system.threading.tasks; namespace stopwatchdemo { class program { static void main(string[] args) { int i = 6000000,m1= 0,m2=0; stopwatch sw = new stopwatch(); sw.start(); for (int k = 0; k <= i; k++) { m1++; } console.writeline(sw.elapsedmilliseconds); sw.restart(); for (int k = 0; k <= i; k+=2) { m2++; } sw.stop(); console.writeline(sw.elapsedmilliseconds); console.readkey(); } } }
到此这篇关于c#使用stopwatch实现计时功能的文章就介绍到这了,更多相关c# stopwatch计时内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论