Big*_*ree 5 c malloc memory-management mmap
我使用mmap编写了1.28亿个内存到分配了malloc的内存和映射的内存文件(由磁盘上的文件支持)的性能测试......我原本期望结果有点相似,因为我的理解是在写入时一个映射的内存文件,数据最初写入内存,pdflush在后台写入磁盘(可以配置的频率).使用malloc,写入128M整数需要0.55秒; mmap花了1.9秒.
所以我的问题是:为什么差异.我的首字母缩写是pdflush挤满了总线,或者当pdflush正在访问内存时,它阻止了写入...但是,第二次运行mmap版本会产生.52秒的结果(由于缓存)导致我相信mmap背后的每个页面都没有被分配,直到它被写入(尽管通过调用mmap保留它)...我也理解,malloc生成的内存直到第一次写入才真正分配. .could最初的区别是因为在malloc初始写入内存后,整个块被分配并使用mmap,每次写入新页面时,os必须首先分配它?
更新:
os:CentOS Linux版本7.0.1406(核心)内核:3.10.0-123.el7.x86_64 gcc:4.8.2
码:
int* pint = malloc(128000000 * sizeof(int));
int* pint_copy = pint;
clock_t start = clock();
int i;
for(i = 0; i < 128000000; ++i)
{
*pint++ = i;
}
clock_t end = clock();
double cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("%f\n", cpu_time_used);
free(pint_copy);
Run Code Online (Sandbox Code Playgroud)
VS
int fd = open("db", O_RDWR | O_CREAT, 0666);
const size_t region_size = ((512000000 / sysconf(_SC_PAGE_SIZE)) + 1) * sysconf(_SC_PAGE_SIZE);
int return_code = ftruncate(fd, region_size);
if (return_code < 0)
printf("mapped memory file could not be truncated: %u\n", return_code);
int* pint = mmap(NULL, region_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
int* pint_copy = pint;
close(fd);
clock_t start = clock();
int i;
for(i = 0; i < 128000000; ++i)
{
*pint++ = i;
}
clock_t end = clock();
double cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("%f\n", cpu_time_used);
fgetc(stdin);
munmap(pint_copy, region_size);
Run Code Online (Sandbox Code Playgroud)
并补充说:
int z = 512;
while(z < 128000000)
{
pint[z] = 0;
z += 1024;
}
Run Code Online (Sandbox Code Playgroud)
之前:
clock_t start = clock();
Run Code Online (Sandbox Code Playgroud)
两次试验产生.37秒,让我相信"触摸"每个页面会导致操作系统分配物理内存(对于mmap和malloc)...也可能部分是因为"触摸"页面会移动一些内存缓存...有没有人知道如果在大量写入内存期间(长时间),pdflush会阻止或减慢内存写入?