c/c++测试程序运行时间

2014-11-23 22:25:52 ? 作者: ? 浏览: 3

算法分析中需要对各种算法进行性能测试,下面介绍两种通用的测试方法,由于只用到标准c语言函数,所以在各种平台和编译器下都能使用。

方法1:

clock()函数

开始计时:start = clock()

结束计时:end = clock()

start和end都是clock_t类型

结果(秒):time = (double)(end - start) / CLOCKS_PER_SEC


#include   
#include   
#include   
#include   
#include   
using namespace std; 
 
inline bool cmp(int a, int b) 
{ 
    return a > b; 
} 
 
const int n = 100000000; 
int a[n]; 
int main() 
{ 
    clock_t start, stop;                 //定义clock_t类型的start和end  
    for (int i = 0; i < n; ++i) 
        a[i] = i; 
    start = clock(); 
    //sort(a, a + n, cmp);                  //开始计时  
    sort(a, a + n, greater());                //中间是需要计时的代码  
    stop = clock();                     //结束计时  
    printf("%f\n", (double)(stop - start) / CLOCKS_PER_SEC); 
    return 0; 
} 

#include 
#include 
#include 
#include 
#include 
using namespace std;

inline bool cmp(int a, int b)
{
 return a > b;
}

const int n = 100000000;
int a[n];
int main()
{
 clock_t start, stop;     //定义clock_t类型的start和end
 for (int i = 0; i < n; ++i)
  a[i] = i;
 start = clock();
 //sort(a, a + n, cmp);     //开始计时
 sort(a, a + n, greater());    //中间是需要计时的代码
 stop = clock();      //结束计时
 printf("%f\n", (double)(stop - start) / CLOCKS_PER_SEC);
 return 0;
}


这段代码对排序中使用自己定义的函数和函数对象的速度进行测试,平均情况下还是函数对象的版本比较快。(当然这种测试不够严谨,仅仅是演示一下计时的方法)


方法2:和上一种方法差不多,只是用时间函数。

time_t start, end;

start = time(NULL);

end = time(NULL);

time = (double)(end - start);


-->

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: