我的多次結果還是memset最快,但網上有說for()迴圈初始化數組比memset快的(在int下),因為memset每次只能操作一個位元組。不知道大家測出來結果如何或這是我的測試程式原理錯了?
- #include <iostream>
- #include <algorithm>
- #include <ctime>
- using namespace std;
- const int n=10000000;
- template<class T>
- class TEST{
- private:
- long out,a1,b1,c1,d1;
- T *a,*b,*c,*d;
- void test_unity(const T &x,const T &y){//memset的賦值有點特殊,所以單獨設定變數x
- clock_t start, finish;
- //a.for memset
- start = clock();
- memset(a,x,sizeof(T)*n);
- finish = clock();
- out=finish-start; a1+=out;
- //cout<<"memset"<<endl;
-
- //b.for for()
- start = clock();
- for(int i=0;i<n;i++) b[i]= y ;
- finish = clock();
- out=finish-start; b1+=out;
- //cout<<"for"<<endl;
-
- //c.for while()
- start = clock();
- int i=0;
- while(i<n) c[i++] = y;
- finish = clock();
- out=finish-start; c1+=out;
- //cout<<"while"<<endl;
- //d.for fill()
- start = clock();
- fill(d,d+n, y );
- finish = clock();
- out=finish-start; d1+=out;
- //cout<<"fill"<<endl;
- }
- public:
- TEST(T x1,T y1,T x2,T y2,T x3,T y3){
- a1=b1=c1=d1=0;
- a=new T[n];
- b=new T[n];
- c=new T[n];
- d=new T[n];
- for(int i=0;i<5;i++){
- test_unity(x1,y1);
- test_unity(x2,y2);
- test_unity(x3,y3);
- }
- cout<<"memset() :"<<a1<<endl
- <<"for() :"<<b1<<endl
- <<"while() :"<<c1<<endl
- <<"fill() :"<<d1<<endl<<endl;
- }
- virtual ~TEST(){
- delete []a;
- delete []b;
- delete []c;
- delete []d;
- }
- };
- int main() {
- cout<<"int:"<<endl;
- TEST<int> test1(-1,-1,0,0,5,84215045);
- //test1.~TEST();
- cout<<"short:"<<endl;
- TEST<short> test2(-1,-1,0,0,5,1285);
- //test2.~TEST();
- cout<<"long:"<<endl;
- TEST<long> test3(-1,-1,0,0,5,84215045);
- //test3.~TEST();
- cout<<"char:"<<endl;
- TEST<char> test4(0,0,'a','a','9','9');
- //test4.~TEST();
- cout<<"bool:"<<endl;
- TEST<bool> test5(0,0,true,true,false,false);
- //test5.~TEST();
- cout<<"long long:"<<endl;
- TEST<long long> test6(-1LL,-1LL,0LL,0LL,5LL,361700864190383365LL);
- //test5.~TEST();
- return 0;
- }
最終結果,memset最快,測試的資料類型的位元組越小越有優勢,foe與while相差無幾,fill最慢,看了下SGI下的fill()的原始碼,採用的是for(;first!=last;first++) *first=val;的方式,然後針對char型的是用的memset,我的理解是因為memset對多位元組的資料類型不能賦成特定的值,所以才採用的for(),也間接說明了memset比for應該要快吧。。
以上僅是個人猜測,不對的地方還望指出,謝謝,發郵件也行,liliflashfly@gmail.com