首页 > 开发 > 综合 > 正文

在C#中实现高性能计时

2024-07-21 02:21:11
字体:
来源:转载
供稿:网友
for performance test, it is very important to measure code execution time. without measurement, there is no way to tell if we meet performance goal.

system.environment.tickcount is not suitable for high resolution timing. its resolution cannot be less than 500 milliseconds.

system.datetime.now returns the current time of type datetime. with start datetime and end datetime, we can get the interval as a value of timespan by (end - start ) . timespan.totalmilliseconds or timespan.ticks may be used to read interval. from msdn, the resolution of system.datetime.now depends on the system timer.

system approximate resolution
windows nt 3.5 and later 10 milliseconds
windows 98 55 milliseconds

so it is better but not high resolution at all.


in .net framework v1 and v1.1, we have to use p/invoke to get high resolution reading. the class below is commonly used in performance test measurement. it is querying hardware to get high resolution performance counter. for more information (including what happens if the hardware does not support high resolution performance counter) please check msdn for queryperformancecounter and queryperformancefrequency.

public class highresolutiontimer
{
private long start;
private long stop;
private long frequency;

public highresolutiontimer()
{
queryperformancefrequency (ref frequency);
}

public void start ()
{
queryperformancecounter (ref start);
}

public void stop ()
{
queryperformancecounter (ref stop);
}

public float elapsedtime
{
get{
float elapsed = (((float)(stop - start)) / ((float) frequency));
return elapsed;
}
}

[system.runtime.interopservices.dllimport("kernel32.dll", charset=system.runtime.interopservices.charset.auto)]
private static extern bool queryperformancecounter( [in, out] ref long performancecount);
[system.runtime.interopservices.dllimport("kernel32.dll", charset=system.runtime.interopservices.charset.auto)]
private static extern bool queryperformancefrequency( [in, out] ref long frequency);
}

to illustrate the use of this class, check the code below.

highresolutiontimer timer = new highresolutiontimer();
timer.start();
//perf test
timer.stop();
console.writeline(timer.elapsedtime);

(this posting is provided "as is" with no warranties, and confers no rights. use of included script samples are subject to the terms specified at http://www.microsoft.com/info/cpyright.htm)



发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表