测试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里面比较快。

猜你喜欢

转载自www.cnblogs.com/litifeng/p/13169750.html