[转]使用Stopwatch类实现高精度计时
对一段代码计时同查通常有三种方法。最简单就是用DateTime.Now来进行比较了,不过其精度只有3.3毫秒,可以通过DllImport导入QueryPerformanceFrequency和QueryPerformanceCounter,实现高精度的计时,请参考《.net平台下获取高精度时间类》。
在.NET 2.0中,新增了Stopwatch类处理计时需求,Stopwatch会优先使用高精度计时,仅当系统不支持时才会用DateTime来计时,可通过Stopwatch静态属性IsHighResolution来判断是否是高精度计时。
Stopwatch最简单的使用示例:
- // 开始计时
- Stopwatch watch = new Stopwatch();
- watch.Start();
- // 你的耗时代码
- // 停止计时
- watch.Stop();
- //得到运行所花费的时间
- Console.WriteLine(watch.Elapsed);
MSDN上的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-10001.
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);
}
}
}
}
msdn:《Stopwatch Class》
[转]使用Stopwatch类实现高精度计时的更多相关文章
- 使用StopWatch类来计时 (perf4j-0.9.16.jar 包里的类)
public class StopWatch { static public int AN_HOUR = 60 * 60 * 1000; static public int A_MINUTE = 60 ...
- C# Stopwatch类_性能_时间计时器
在研究性能的时候,完全可以使用Stopwatch计时器计算一项技术的效率.但是有时想知道某想技术的性能的时候,又常常想不起可以运用Stopwatch这个东西,太可悲了. 属性: Elapsed 获取当 ...
- Stopwatch 类【转】
一般我们想要测试使用那种方法或着那种类型效率更高,使用Stopwatch类进行测试就可以,我也是现在才知道,汗一个. 先来看个小示例,如下. 前提,先引用using System.Diagnostic ...
- Stopwatch类学习
1.概述:给一条大MSDN的链接关于Stopwatch类最详细的教程 ,然后看着教程自己手动敲一边,加深映象,好记性不如烂键盘,哈哈,开个玩笑! 2.类位置:这个类在哪里,这个是重点,虽然C#IDE很 ...
- C# Stopwatch 类
命名空间:System.Diagnostics Stopwatch 实例可以测量一个时间间隔的运行时间,也可以测量多个时间间隔的总运行时间.在典型的 Stopwatch 方案中,先调用 Start 方 ...
- Stopwatch 类用于计算程序运行时间
Stopwatch 类 命名空间:System.Diagnostics.Stopwatch 实例化:Stopwatch getTime=new Stopwatch(); 开始计时:getTime.St ...
- C#基础_利用Stopwatch计时器可暂停计时,继续计时
最近程序上用到了计时功能,对某个模块进行计时,暂停的时候模块也需要暂停,启动的时候计时继续 用到了Stopwatch Stopwatch的命名空间是using System.Diagnostics; ...
- 用Stopwatch类获得程序运行时间
我们可以用Stopwatch类获得程序的运行时间,在优化代码时,可以用此方法来查看优化前后程序所耗费的时间 //Stopwatch类別在System.Diagnostics命名空间里 Stopwatc ...
- 利用StopWatch类监控Java代码执行时间并分析性能
springframework中的StopWatch类可以测量一个时间间隔的运行时间,也可以测量多个时间间隔的总运行时间.一般用来测量代码执行所用的时间或者计算性能数据,在优化代码性能上可以使用Sto ...
随机推荐
- leetcode 383. Ransom Note
Given an arbitrary ransom note string and another string containing letters from all th ...
- bash里面的一些符号说明
$$ Shell本身的PID(ProcessID) $! Shell最后运行的后台Process的PID $? 最后运行的命令的结束代码(返回值) $- 使用Set命令设定的Flag一览 $* 所有参 ...
- 添加到SQLAgentReaderRole角色后报拒绝SELECT权限
最近有点大意,同事需要查看作业的权限,"理所当然"就将对应登录名添加到SQLAgentReaderRole角色. msdb的SQLAgentReaderRole数据库角色的成员继承 ...
- Asp.Net Razor中的Consistent Layout
有意义的参考:http://www.asp.net/web-pages/tutorials/working-with-pages/3-creating-a-consistent-look Asp.ne ...
- MyEclipse开发Java Web项目步骤
1.安装工具 第一步,下载安装JDK,并配置环境: 配置环境变量步骤: (1)新建变量名:JAVA_HOME,变量值为JDK的安装路径: (2)打开PATH,添加变量值:%JAVA_HOME%\bin ...
- Android Studio Jni 环境搭建
第一步:NDK环境搭建,点击下图红色框区域查看NDK下载和环境配置 安照正常情况是很慢的或者无法下载成功的,这个时候可以去下载NDK压缩包进行解压.下面给出两个下载地址 (1)官网:http://we ...
- BufferedReader与Scanner的区别
在Java中,我们都知道Java的标准输入串是System.in.但是我们却很少在Java中看到谁使用它,这是因为我们平时输入的都是一个字符串或者是一个数字等等.而System.in提供的read方法 ...
- pod install 无限卡顿
pod install 被墙了,请大家换成pod install --verbose --no-repo-update
- SQLServer2008R2企业版密匙
SQLServer2008R2企业版密匙: R88PF-GMCFT-KM2KR-4R7GB-43K4B
- Best Part