zoukankan      html  css  js  c++  java
  • C/C++ 测试代码运行时间

    今天在学习浙大的数据结构课程,陈越老师让我们写代码来比较迭代和递归的性能差别,遂使用了ctime or time.h中的clock函数来计算程序运行耗时。

    方法

    #include<ctime>
    
    int main(){
      clock_t start, finish; // 用来保存当前时钟的变量类型
       
      start = clock(); // 调用clock函数获取当前时钟
      .....
      finish = clock(); 
       
      double duration = (double)(finish - start) / CLOCKS_PER_SEC  // CLOCKS_PER_SEC为定义在ctime中的常量
    }
    

    示例

    比较递归与迭代的printN函数的性能:

    #include<iostream>
    #include<ctime>
    #include<vector>
    using namespace std;
    
    void printN_v1(int n){
        for (int i = 1; i <= n; i++){
            cout << n;
        }
        cout << endl;
    }
    
    void printN_v2(int n){
        if (n){
            printN_v2(n-1);
            cout << n;
        }
        cout << endl;
    }
    
    int main(){
        int N[] = {10, 100, 1000, 10000}; // 测试数据 
        double duration;
        vector<double> t1;  // 迭代耗时 
        vector<double> t2;  // 递归耗时 
        
        clock_t start, finish;
        for (int i = 0; i < 4; i++){
            start = clock();
            printN_v1(N[i]);
            finish = clock();
            duration = (double)(finish - start) / CLOCKS_PER_SEC;
            t1.push_back(duration);
            
            start = clock();
            printN_v2(N[i]);
            finish = clock();
            duration = (double)(finish - start) / CLOCKS_PER_SEC;
            t2.push_back(duration);
        }
        
        cout << endl << "	Iteration 	recursion" << endl;
        for (int i = 0; i < t1.size(); i++){
            cout << N[i] << ":	" << t1[i] << "		" << t2[i] << endl;
        }
        
        return 0;
    }
    
    CS专业在读,热爱编程。
    专业之外,喜欢阅读,尤爱哲学、金庸、马尔克斯。
  • 相关阅读:
    sharepoint JQ获取List列表的值
    微信修改域名回掉
    input设置只读
    MVC-AJAX-JSON
    sharepoint添加子网站
    sharepoint打开解决方案库
    前台获取参数值
    SQL查看表结构以及表说明
    JQ获取对象属性值
    bootstrap table样式
  • 原文地址:https://www.cnblogs.com/jmhwsrr/p/14592870.html
Copyright © 2011-2022 走看看