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

作者:暴躁小n | 创建时间: 2023-04-18
c/c++测试程序运行时间

操作方法

算法分析中需要对各种算法进行性能测试,下面介绍两种通用的测试方法,由于只用到标准c语言函数,所以在各种平台和编译器下都能使用。 方法1: clock()函数 开始计时:start = clock() 结束计时:end = clock() start和end都是clock_t类型 结果(秒):time = (double)(end - start) /  CLOCKS_PER_SEC #include <iostream> #include <cstdio> #include <ctime> #include <algorithm> #include <functional> 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;<SPAN style="WHITE-SPACE: pre">                 </SPAN>//定义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<int>());<SPAN style="WHITE-SPACE: pre">                </SPAN>//中间是需要计时的代码 stop = clock();                     //结束计时 printf("%f\n", (double)(stop - start) / CLOCKS_PER_SEC); return 0; } #include <iostream> #include <cstdio> #include <ctime> #include <algorithm> #include <functional> 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<int>());    //中间是需要计时的代码 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);

点击展开全文

更多推荐