欢迎光临
我们一直在努力

在C#中实现高性能计时-.NET教程,VB.Net语言

建站超值云服务器,限时71元/月

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)

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » 在C#中实现高性能计时-.NET教程,VB.Net语言
分享到: 更多 (0)