我的多次结果还是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
这篇博客探讨了在C++中使用memset、for循环、while循环和fill()初始化数组的效率问题。实验结果显示memset通常最快,fill()最慢,且对于不同数据类型,memset的优势更为明显。博主通过源码分析认为,fill()对多字节类型使用for循环,而memset适用于字节类型,这可能是memset表现更好的原因。
1131

被折叠的 条评论
为什么被折叠?



