手机
当前位置:查字典教程网 >编程开发 >C#教程 >C#计算代码执行时间的方法
C#计算代码执行时间的方法
摘要:最近遇到一个模块其执行时间非常短,但是调用频率非常高。精确计算其运算时间对于提高程序整体效率来说非常重要。在我刚刚接触.Net时,也曾经想要...

最近遇到一个模块其执行时间非常短,但是调用频率非常高。精确计算其运算时间对于提高程序整体效率来说非常重要。

在我刚刚接触.Net时,也曾经想要测试一下自己写的程序的运行时间,当时我使用的是将两个DateTime.Now相减的笨方法,呵呵。后来知道使用Environment.TickCount,对于一般的测试来说就足够了。但是它对于高精度测试就没什么办法,经常是返回个0了事。对于高精度测试我们应当使用QueryPerformanceFrequency函数和QueryPerformanceCounter函数。通过它们可以获得比Environment.TickCount更高的精确度。实际上Environment.TickCount就是在调用QueryPerformanceFrequency函数和QueryPerformanceCounter函数。

下面是我使用的代码:

复制代码 代码如下:

using System;

class Class1

{

[System.Runtime.InteropServices.DllImport ("Kernel32.dll")]

static extern bool QueryPerformanceCounter(ref long count);

[System.Runtime.InteropServices.DllImport ("Kernel32.dll")]

static extern bool QueryPerformanceFrequency(ref long count);

[STAThread]

static void Main(string[] args)

{

long count = 0;

long count1 = 0;

long freq = 0;

double result = 0;

QueryPerformanceFrequency(ref freq);

QueryPerformanceCounter(ref count);

//需要测试的模块

QueryPerformanceCounter(ref count1);

count = count1-count;

result = (double)(count)/(double)freq;

Console.WriteLine("耗时: {0} 秒", result);

Console.ReadLine();

}

}

这样能够得到非常精确的结果。但是模块每次运行的时间总会有些误差,而当计算非常精确的时候,这些运行时间的误差也显得比较明显了。为此我对其进行循环多次测试使其误差平均化,通过多次测试的结果来进行执行效率的分析。

复制代码 代码如下:

using System;

class Class1

{

[System.Runtime.InteropServices.DllImport ("Kernel32.dll")]

static extern bool QueryPerformanceCounter(ref long count);

[System.Runtime.InteropServices.DllImport ("Kernel32.dll")]

static extern bool QueryPerformanceFrequency(ref long count);

[STAThread]

static void Main(string[] args)

{

long count = 0;

long count1 = 0;

long freq = 0;

double result = 0;

QueryPerformanceFrequency(ref freq);

QueryPerformanceCounter(ref count);

//开始的时候没有这层循环,所得数据浮动很大,添加这层循环来使得结果更加平均

for (int i=0; i<500; i++)

{

//需要测试的模块

}

QueryPerformanceCounter(ref count1);

count = count1-count;

result = (double)(count)/(double)freq;

Console.WriteLine("耗时: {0} 秒", result);

Console.ReadLine();

}

}

C#中的秒表 计算程序运行了多长时间 System.Diagnostics.Stopwatch

复制代码 代码如下:

private void button1_Click(object sender, EventArgs e)

{

Stopwatch myWatch = new Stopwatch();

myWatch.Start();

for (int i = 0; i < 1000; i++)

{

Console.WriteLine("just test" + i);

}

myWatch.Stop();

long myUseTime = myWatch.ElapsedMilliseconds;

MessageBox.Show("執行時間: " + myUseTime.ToString() + " ms");

}

【C#计算代码执行时间的方法】相关文章:

解决C#中WebBrowser的DocumentCompleted事件不执行的实现方法

C#使用DllImport调用非托管的代码的方法

C# 禁用鼠标中间键的方法

C#中计算时间差中的小数问题解决

C# 读取指定路径配置文件的方法

获得.net控件的windows句柄的方法

c#在控制台输出彩色文字的方法

C#操作注册表的方法

C# 获取属性名的方法

C#中控制远程计算机的服务的方法

精品推荐
分类导航