最近一直在做图论的题目。对于初始化的效率要求比较高。正巧我也对这三个函数不是很清楚。
就写了个测试程序来测试效率
测试程序:
#include <bits/stdc++.h> //#pragma GCC optimize(2) using namespace std; #define max 100000000+5 int a[max]; int main() { time_t beg,end; cout<<"---------------------------for "; beg=clock(); for(int i=0;i<max;++i) a[i]=0; end=clock(); cout<<"test 1 cost: "<<end-beg<<"MS"<<endl; beg=clock(); for(int i=0;i<max;++i) a[i]=0; end=clock(); cout<<"test 2 cost: "<<end-beg<<"MS"<<endl; beg=clock(); for(int i=0;i<max;++i) a[i]=0; end=clock(); cout<<"test 3 cost: "<<end-beg<<"MS"<<endl; beg=clock(); for(int i=0;i<max;++i) a[i]=0; end=clock(); cout<<"test 4 cost: "<<end-beg<<"MS"<<endl; beg=clock(); for(int i=0;i<max;++i) a[i]=0; end=clock(); cout<<"test 5 cost: "<<end-beg<<"MS"<<endl; beg=clock(); for(int i=0;i<max;++i) a[i]=0; end=clock(); cout<<"test 6 cost: "<<end-beg<<"MS"<<endl; cout<<"----------------register---for "; beg=clock(); for(register int i=0;i<max;++i) a[i]=0; end=clock(); cout<<"test 1 cost: "<<end-beg<<"MS"<<endl; beg=clock(); for(register int i=0;i<max;++i) a[i]=0; end=clock(); cout<<"test 2 cost: "<<end-beg<<"MS"<<endl; beg=clock(); for(register int i=0;i<max;++i) a[i]=0; end=clock(); cout<<"test 3 cost: "<<end-beg<<"MS"<<endl; beg=clock(); for(register int i=0;i<max;++i) a[i]=0; end=clock(); cout<<"test 4 cost: "<<end-beg<<"MS"<<endl; beg=clock(); for(register int i=0;i<max;++i) a[i]=0; end=clock(); cout<<"test 5 cost: "<<end-beg<<"MS"<<endl; beg=clock(); for(register int i=0;i<max;++i) a[i]=0; end=clock(); cout<<"test 6 cost: "<<end-beg<<"MS"<<endl; cout<<"---------------------------fill "; beg=clock(); fill(a,a+max,0); end=clock(); cout<<"test 1 cost: "<<end-beg<<"MS"<<endl; beg=clock(); fill(a,a+max,0); end=clock(); cout<<"test 2 cost: "<<end-beg<<"MS"<<endl; beg=clock(); fill(a,a+max,0); end=clock(); cout<<"test 3 cost: "<<end-beg<<"MS"<<endl; beg=clock(); fill(a,a+max,0); end=clock(); cout<<"test 4 cost: "<<end-beg<<"MS"<<endl; beg=clock(); fill(a,a+max,0); end=clock(); cout<<"test 5 cost: "<<end-beg<<"MS"<<endl; beg=clock(); fill(a,a+max,0); end=clock(); cout<<"test 6 cost: "<<end-beg<<"MS"<<endl; cout<<"---------------------------memset "; beg=clock(); memset(a,0,sizeof(a)); end=clock(); cout<<"test 1 cost: "<<end-beg<<"MS"<<endl; beg=clock(); memset(a,0,sizeof(a)); end=clock(); cout<<"test 2 cost: "<<end-beg<<"MS"<<endl; beg=clock(); memset(a,0,sizeof(a)); end=clock(); cout<<"test 3 cost: "<<end-beg<<"MS"<<endl; beg=clock(); memset(a,0,sizeof(a)); end=clock(); cout<<"test 4 cost: "<<end-beg<<"MS"<<endl; beg=clock(); memset(a,0,sizeof(a)); end=clock(); cout<<"test 5 cost: "<<end-beg<<"MS"<<endl; beg=clock(); memset(a,0,sizeof(a)); end=clock(); cout<<"test 6 cost: "<<end-beg<<"MS"<<endl; return 0; }
开启o2优化之后
综上,当需要数组初始化为0,-1,inf时,memset最快,
其他时候,循环赋值 + O2优化最快