• 测试c++函数的运行时间


    clock()函数返回从“开启这个程序进程”到“程序中调用clock()函数”时之间的CPU时钟计时单元(clock tick)数,在MSDN中称之为挂钟时间(wal-clock)常量CLOCKS_PER_SEC,它用来表示一秒钟会有多少个时钟计时单元。

    比如:我想知道vector在2种情况下的运行效率:

    #include<iostream>
    #include<algorithm>
    #include<vector>
    #include<ctime>  //时间函数,包括clock函数
    using namespace std;
    typedef pair<int, int> point;
    vector<point> vp1;
    int main() {
        int n = 100000;
        vector<point>vp2(n);
        clock_t start, stop;
        start = clock();
        for (int i = 0; i < n; i++) {
            point t;
            t.first = i;
            t.second = i;
            vp1.push_back(t);
        }
        stop = clock();
        cout <<"vp1:"<< stop - start << endl;
        start = clock();
        for (int i = 0; i < n; i++) {
            point t;
            t.first = i;
            t.second = i;
            vp2[i] = t;
        }
        stop = clock();
        cout <<"vp2: "<< stop - start << endl;
        return 0;
    }

     输出:

    vp1:71
    vp2: 5

    经过测试:还是把vector函数写在main里面比较快。

  • 相关阅读:
    第十九天:类和对象
    第十五天:模块
    十四天:匿名函数
    十四天作业
    第十三天:迭代器、递归
    十二天:闭包和装饰器
    一个炒鸡简单的购物车
    十一天
    第十天
    第十天作业
  • 原文地址:https://www.cnblogs.com/litifeng/p/13169750.html
Copyright © 2020-2023  润新知