#include
<
iostream
>
#include < time.h >
#include < stddef.h >
#include < string .h >
using namespace std;
void copy_with_pointers( char const * src, char * dst,size_t n)
... {
for(size_t k=0;k!=n;++k)
*dst++=*src++;
}
void copy_with_indices( char const * src, char * dst,size_t n)
... {
for(size_t k=0;k!=n;++k)
dst[k]=src[k];
}
int main()
... {
int const n_bytes=100000;
int const n_calls=100;
char *src=new char[n_bytes];
char *dst=new char[n_bytes];
memcpy(dst,src,n_bytes);
clock_t start,end,reftime;
start=clock();
for(int k=0;k!=n_calls;++k)
memcpy(dst,src,n_bytes);
end=clock();
cout<<"Time with memcpy: "<<rend-start<<endl;
start=clock();
for(int k=0;k!=n_calls;++k)
copy_with_pointers(src,dst,n_bytes);
end=clock();
cout<<"Time with pointer: "<<end-start<<endl;
start=clock();
for(int k=0;k!=n_calls;++k)
copy_with_indices(src,dst,n_bytes);
end=clock();
cout<<"Time with indices: "<<end-start<<endl;
delete[] src;
delete[] dst;
return 0;
}
#include < time.h >
#include < stddef.h >
#include < string .h >
using namespace std;
void copy_with_pointers( char const * src, char * dst,size_t n)
... {
for(size_t k=0;k!=n;++k)
*dst++=*src++;
}
void copy_with_indices( char const * src, char * dst,size_t n)
... {
for(size_t k=0;k!=n;++k)
dst[k]=src[k];
}
int main()
... {
int const n_bytes=100000;
int const n_calls=100;
char *src=new char[n_bytes];
char *dst=new char[n_bytes];
memcpy(dst,src,n_bytes);
clock_t start,end,reftime;
start=clock();
for(int k=0;k!=n_calls;++k)
memcpy(dst,src,n_bytes);
end=clock();
cout<<"Time with memcpy: "<<rend-start<<endl;
start=clock();
for(int k=0;k!=n_calls;++k)
copy_with_pointers(src,dst,n_bytes);
end=clock();
cout<<"Time with pointer: "<<end-start<<endl;
start=clock();
for(int k=0;k!=n_calls;++k)
copy_with_indices(src,dst,n_bytes);
end=clock();
cout<<"Time with indices: "<<end-start<<endl;
delete[] src;
delete[] dst;
return 0;
}
100000大小的数组拷贝100次,比较三种方式谁更快(memcpy, 指针,数组),编译器GUN C++
首先用C <string.h>里的库函数memcpy,运行多次后看到大部分的结果是0,有少量是16
然后用指针拷贝的方式,稳定在46,但偶尔会飙到63左右。
最后是数组下标,时间在62左右,最高78,不过有时也会降到46,但这个时候指针拷贝的时间大部分是64,也会稳在46,47
多次比较的结果,还是C函数速度最快,不过只适用与初始化数组为同一个值。而指针相对于数组下标稍快一些。当然这个实验中还有函数进栈、出栈的时间使得指针和下标时间较长。
(这里clock() 的时间单位是,CPU时钟滴答一下为一次)