#include<iostream>
#include<iomanip>
#include<time.h>
#include<vector>
#include<algorithm>
#include<iterator>
#include<numeric>
using namespace std;
int main(int argc,char* argv[])
{
int SIZE = 1024*1024*64;
int val = 0x0f0f0f0f;
int *buf = new int[SIZE];
clock_t beg = clock();
memset(buf,val,SIZE);
clock_t memset_fun = clock();
for(int i = 0; i < SIZE; i++)
buf[i] = val;
clock_t for_loop = clock();
cout<<"memset function: "<<memset_fun - beg<<endl<<"for loop: "<<for_loop - memset_fun;
cout<<hex<<endl<<buf[0]<<endl;
cout<<endl<<(((int)buf) & 3)<<endl;
system("pause");
return 0;
}
输出结果是:
memset function: 61
for loop: 288
f0f0f0f0
0
问题是:
memset()比for 循环快很正常,但是我的是在release 状态下测试的,且看反汇编:
18: clock_t beg = clock();
003E1045 mov edi,dword ptr [__imp__clock (3E20D4h)]
003E104B add esp,4
003E104E mov esi,eax
003E1050 call edi
19: memset(buf,val,SIZE);
003E1052 push 4000000h
003E1057 push 0F0F0F0Fh
003E105C push esi
003E105D mov dword ptr [esp+18h],eax
003E1061 call memset (3E1C2Ah)
003E1066 add esp,0Ch
20: clock_t memset_fun = clock();
003E1069 call edi
003E106B mov ebx,eax
21:
22: for(int i = 0; i < SIZE; i++)
23: buf[i] = val;
003E106D mov eax,0F0F0F0Fh
003E1072 mov ecx,4000000h
003E1077 mov edi,esi
003E1079 rep stos dword ptr es:[edi]
24:
25: clock_t for_loop = clock();
003E107B call dword ptr [__imp__clock (3E20D4h)]
注意倒数等四行:我的for 循环已经被优化成了rep stos dword ptr es:[edi]
这个跟memset()里面的核心语句是一样的。而且,输出结果表明指针的确是在4字节整数倍上的,单步跟踪也发现memset()并没有做什么特别的动作才执行rep stosd 。 可是为什么??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
为什么memset()就是要比我的for循环快???????而且多次测试结果表明,for循环用的时间是memset()的6-3倍?????????????????????????????????????
为什么???????????????????????????
注:也不是clock()函数的影响。
大牛快回答啊。