提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
目录
问题引入
在C++程序的性能分析中,其中重要的一项就是程序的运行时间。虽然程序的运行速度与计算机的配置、计算机的当前状态等有很大关系,但在相对一致的外部环境下,程序运行时间的长短在很大程度上是可以反映程序效率的。
一、一般计时方法
在ctime头文件中,C++提供了计时函数 clock() ,其返回数据类型为 clock_t。
typedef long clock_t;
clock()函数返回从“开启程序进程”到“程序中调用clock()函数”这段时间里,CPU时钟计时单元(clock tick)的数目,在MSDN中称之为挂钟时间(wal-clock)。
在ctime文件中,还定义了一个常量CLOCKS_PER_SEC,它用来表示一秒内有多少个CPU时钟计时单元。
通过clock()/CLOCKS_PER_SEC便可以得到进程的运行时间,一般CLOCKS_PER_SEC的值为1000,可见计时精度可达小数点后3位(毫秒级)。
/*
随机生成数组,并用冒泡排序处理数据,计算程序运行时间,评估算法的效率。
*/
#include <iostream>
#include <ctime>
using namespace std;
int a[100000];
//定义clock_t变量,估算循环运行时间
void bubble_sort(int a[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (a[j]>a[j+1]) {
swap(a[j], a[j + 1]);
}
}
}
}
int main() {
int n;
cin>>n;
srand(time(0));
for(int i = 0;i<n;i++){
a[i] = rand() % 1000 + 1;
}
cout<<"-----------------排序前-----------------"<<endl;
for(int i = 0;i<n;i++){
cout<<a[i]<<" ";
}
cout<<endl;
cout<<"-----------------排序后-----------------"<<endl;
clock_t begin,end;
begin = clock();
bubble_sort(a,n);//计算排序需要多长时间
end = clock();
for(int i = 0;i<n;i++){
cout<<a[i]<<" ";
}
cout<<endl;
cout<<"-----------------排序用时(ms)-----------------"<<endl;
cout<<end - begin;
return 0;
}
二、精确计时方法
这里精确的含义是计时的精度更高,使用QueryPerformanceCounter()和QueryPerformanceFrequency(),计算机从硬件上支持精确定时器。
QueryPerformanceCounter()函数返回高精确度计数器的脉冲数目(计时数),QueryPerformanceFrequency()函数提供了高精度计时器的频率值,即每秒脉冲数。
/*
随机生成数组,并用冒泡排序处理数据,计算程序运行时间,评估算法的效率。
*/
#include <algorithm>
#include<windows.h>
#include <iostream>
#include <ctime>
using namespace std;
int a[100000];
//定义clock_t变量,估算循环运行时间
void bubble_sort(int a[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (a[j]>a[j+1]) {
swap(a[j], a[j + 1]);
}
}
}
}
int main() {
int n;
cin>>n;
LARGE_INTEGER nFreq;
LARGE_INTEGER t1;
LARGE_INTEGER t2;
LARGE_INTEGER t3;
LARGE_INTEGER t4;
double dt;
QueryPerformanceFrequency(&nFreq);
srand(time(0));
for(int i = 0;i<n;i++){
a[i] = rand() % 1000 + 1;
}
cout<<"-----------------排序前-----------------"<<endl;
for(int i = 0;i<n;i++){
cout<<a[i]<<" ";
}
cout<<endl;
cout<<"-----------------排序后-----------------"<<endl;
// clock_t begin,end;
// begin = clock();
QueryPerformanceCounter(&t1);
bubble_sort(a,n);//计算排序需要多长时间
QueryPerformanceCounter(&t2);
// end = clock();
for(int i = 0;i<n;i++){
cout<<a[i]<<" ";
}
cout<<endl;
// cout<<"-----------------排序用时(ms)-----------------"<<endl;
cout<<"-----------------排序用时(us)-----------------"<<endl;
dt = (t2.QuadPart - t1.QuadPart) / (double)nFreq.QuadPart;
cout << "Running time :" << dt * 1000000 << "us" << endl;//dt
// cout<<end - begin;
return 0;
}