foo*_*ool 6 malloc performance gcc memcpy cpu-cache
我写了一个测试速度的程序memcpy()
.但是,如何分配内存会极大地影响速度.
#include<stdlib.h>
#include<stdio.h>
#include<sys/time.h>
void main(int argc, char *argv[]){
unsigned char * pbuff_1;
unsigned char * pbuff_2;
unsigned long iters = 1000*1000;
int type = atoi(argv[1]);
int buff_size = atoi(argv[2])*1024;
if(type == 1){
pbuff_1 = (void *)malloc(2*buff_size);
pbuff_2 = pbuff_1+buff_size;
}else{
pbuff_1 = (void *)malloc(buff_size);
pbuff_2 = (void *)malloc(buff_size);
}
for(int i = 0; i < iters; ++i){
memcpy(pbuff_2, pbuff_1, buff_size);
}
if(type == 1){
free(pbuff_1);
}else{
free(pbuff_1);
free(pbuff_2);
}
}
Run Code Online (Sandbox Code Playgroud)
操作系统是linux-2.6.35,编译器是GCC-4.4.5,选项"-std = c99 -O3".
在我的计算机上的结果(memcpy
4KB,迭代100万次):
时间./test.test 1 4
real 0m0.128s
user 0m0.120s
sys 0m0.000s
Run Code Online (Sandbox Code Playgroud)
时间./test.test 0 4
real 0m0.422s
user 0m0.420s
sys 0m0.000s
Run Code Online (Sandbox Code Playgroud)
此问题与之前的问题有关:
原因与GCC编译器有关,我用不同版本的GCC编译和运行该程序:
GCC版-------- 4.1.3
-------- 4.4.5
--------4.6.3
使用时间(1)----- 0m0.183s
---- 0m0.128s
----0m0.110s
使用时间(0)----- 0m1.788s
---- 0m0.422s
----0m0.108s
看起来GCC越来越聪明了.
malloc 返回的特定地址是由实现选择的,并不总是最适合使用的代码。您已经知道移动内存的速度很大程度上取决于缓存和页面效果。
这里,具体分配的指针是未知的。您可以使用 打印它们printf("%p", ptr)
。然而,众所周知的是,对两个块仅使用一个 malloc 肯定可以避免两个块之间的页面和高速缓存浪费。这可能已经是速度差异的原因。