[转]使用Stopwatch类实现高精度计时

对一段代码计时同查通常有三种方法。最简单就是用DateTime.Now来进行比较了,不过其精度只有3.3毫秒,可以通过DllImport导入QueryPerformanceFrequency和QueryPerformanceCounter,实现高精度的计时,请参考《.net平台下获取高精度时间类》。
在.NET
2.0中,新增了Stopwatch类处理计时需求,Stopwatch会优先使用高精度计时,仅当系统不支持时才会用DateTime来计时,可通过Stopwatch静态属性IsHighResolution来判断是否是高精度计时。

Stopwatch最简单的使用示例:

  1. // 开始计时

  2. Stopwatch watch = new Stopwatch();

  3. watch.Start();
  4. // 你的耗时代码
  5. // 停止计时

  6. watch.Stop();
  7. //得到运行所花费的时间

  8. 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

原文:http://www.it118.org/Specials/321869dd-98cb-431b-b6d2-82d973cd739d/3a6ef558-4596-459e-9918-93da13b3bb9b.htm

时间: 2024-07-29 20:07:38

[转]使用Stopwatch类实现高精度计时的相关文章

程序计时器Stopwatch类的运用

Stopwatch提供了几个方法用以控制Stopwatch对象.Start方法开始一个计时操作,Stop方法停止计时.此时如果第二次使用Start方法,将继续计时,最终的计时结果为两次计时的累加.为避免这种情况,在第二次计时前用Reset方法将对象归零.这三个方法都不需要参数. 命名空间:System.Diagnostics 构造函数:Stopwatch sw=new Stopwatch( ); 方法: Start  开始或继续测量某个时间间隔的运行时间. Stop  停止测量某个时间间隔的运行

Stopwatch类,性能,时间计时器

在研究性能的时候,完全可以使用Stopwatch计时器计算一项技术的效率.但是有时想知道某想技术的性能的时候,又常常想不起可以运用Stopwatch这个东西,太可悲了. 属性: Elapsed 获取当前实例测量得出的总运行时间. ElapsedMilliseconds  获取当前实例测量得出的总运行时间(以毫秒为单位). ElapsedTicks  获取当前实例测量得出的总运行时间(用计时器计时周期表示). IsRunning   获取一个指示 Stopwatch 计时器是否在运行的值. 方法

Stopwatch 类

https://msdn.microsoft.com/zh-cn/library/system.diagnostics.stopwatch.aspx 提供一组方法和属性,可用于准确地测量运行时间. 一个 Stopwatch 实例可以测量运行时间为一个时间间隔或所用的时间合计多个间隔. 在典型 Stopwatch 方案中,调用 Start 方法,然后最终调用 Stop 方法,然后检查经过的时间使用 Elapsed 属性. 一个 Stopwatch 实例正在运行或已停止; 使用 IsRunning 

VB6高精度计时类模块

创建一个类模块,粘贴如下代码: '大整数结构体 Private Type LARGE_INTEGER LowPart As Long HighPart As Long End Type '获取时间计数器计数值 Private Declare Function QueryPerformanceCounter _ Lib "kernel32" (lpPerformanceCount As LARGE_INTEGER) As Long '获取震动频率:一个大整数 Private Declar

Windows 计算程序运行时间(高精度计时)

首先,认识一下clock()和GetTickCount(): 一.clock()clock()是C/C++中的计时函数,而与其相关的数据类型是clock_t.在MSDN中,查得对clock函数定义如下:clock_t clock(void) ;简单而言,就是该程序从启动到函数调用占用CPU的时间.这个函数返回从“开启这个程序进程”到“程序中调用clock()函数”时之间的CPU时钟计时单元(clock tick)数,在MSDN中称之为挂钟时间(wal-clock):若挂钟时间不可取,则返回-1.

BigDecimal类(高精度小数)

位置:java.math.BigDecimal 作用:提供高精度小数数据类型及相关操作 一.基本介绍 BigDecimal为不可变的.任意精度的有符号十进制数,其值为(unscaledValue * 10-scale)其中,unscaledValue(非标度值)为任意精度的整数.scale(标度)为32位整型(可为负) 提供以下操作:算术.标度操作.舍入.比较.哈希算法和格式转换. 用户能通过提供MathContext对象完全控制BigDecimal的舍入行为(也可使用类内提供的8种舍入模式).

BigInteger类(高精度整型)

位置:java.math.BigInteger 作用:提供高精度整型数据类型及相关操作 一.基本介绍 BigInteger为不可变的任意精度的整数. 所有操作中,都以二进制补码形式表示 BigInteger(同Java 的基本整数类型). 提供所有 Java 的基本整数操作符(* / + -等等)的对应物(一堆函数). 提供 java.lang.Math 的所有相关方法,此外还提供模算术.GCD 计算.质数测试.素数生成.位操作以及一些其他操作. 算术运算.逐位逻辑运算的语义完全模仿 Java

树莓派高级GPIO库,wiringpi2 for python使用笔记(二)高精度计时、延时函数

学过单片机的同学应该清楚,我们在编写传感器驱动时,需要用到高精度的定时器.延时等功能,wiringpi提供了一组函数来实现这些功能,这些函数分别是: micros() #返回当前的微秒数,这个数在调用wiringPiSetup()后被清零并重新计时 millis() #返回当前的毫秒数,同上,这个数在调用wiringPiSetup()后被清零并重新计时 delayMicroseconds() #高精度微秒延时 delay() #毫秒延时. python相对于C,一个很大的问题就是执行速度慢,所以

windows下C++高精度计时

写代码时,经常会计算某一段代码的运行时间,以下提供一个微秒级别的类供参考 class CTimeCost { public: CTimeCost(const string &str) : m_str(str) { QueryPerformanceFrequency(&m_freg); QueryPerformanceCounter(&m_begin); } ~CTimeCost() { LARGE_INTEGER end; QueryPerformanceCounter(&