我有一个应用程序,从文件中顺序读取数据。一些数据直接从映射文件的指针读取,另一些数据从文件复制到另一个缓冲区。当进行需要大量内存(1MB块)的大型memcpy
时,性能表现不佳,而进行许多较小的memcpy
调用时,性能表现更好(在我的测试中,我使用了4KB,即页面大小,运行时间为大块的1/3)。我认为问题是在进行大型memcpy
时出现了大量的主要页面错误。
我尝试了各种调整参数(MAP_POPULATE
、MADV_WILLNEED
、MADV_SEQUENTIAL
),但没有任何明显的改善。
我不确定为什么很多小的memcpy
调用应该更快;这似乎是违反直觉的。有没有办法改进这个问题?
结果和测试代码如下。
在 CentOS 7 (linux 3.10.0) 上运行,默认编译器 (gcc 4.8.5),从常规磁盘的 RAID 数组中读取 29GB 文件。
使用 /usr/bin/time -v
运行:
4KB memcpy
:
User time (seconds): 5.43
System time (seconds): 10.18
Percent of CPU this job got: 75%
Elapsed (wall clock) time (h:mm:ss or m:ss): 0:20.59
Major (requiring I/O) page faults: 4607
Minor (reclaiming a frame) page faults: 7603470
Voluntary context switches: 61840
Involuntary context switches: 59
1MB memcpy
:
User time (seconds): 6.75
System time (seconds): 8.39
Percent of CPU this job got: 23%
Elapsed (wall clock) time (h:mm:ss or m:ss): 1:03.71
Major (requiring I/O) page faults: 302965
Minor (reclaiming a frame) page faults: 7305366
Voluntary context switches: 302975
Involuntary context switches: 96
MADV_WILLNEED
对1MB的复制结果似乎没有太大影响。
MADV_SEQUENTIAL
显著地减缓了1MB复制结果,我没有等待它完成(至少7分钟)。
MAP_POPULATE
使1MB复制结果变慢了约15秒。
用于测试的简化代码:
#include <algorithm>
#include <iostream>
#include <stdexcept>
#include <fcntl.h>
#include <stdint.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
int
main(int argc, char *argv[])
{
try {
char *filename = argv[1];
int fd = open(filename, O_RDONLY);
if (fd == -1) {
throw std::runtime_error("Failed open()");
}
off_t file_length = lseek(fd, 0, SEEK_END);
if (file_length == (off_t)-1) {
throw std::runtime_error("Failed lseek()");
}
int mmap_flags = MAP_PRIVATE;
#ifdef WITH_MAP_POPULATE
mmap_flags |= MAP_POPULATE; // Small performance degredation if enabled
#endif
void *map = mmap(NULL, file_length, PROT_READ, mmap_flags, fd, 0);
if (map == MAP_FAILED) {
throw std::runtime_error("Failed mmap()");
}
#ifdef WITH_MADV_WILLNEED
madvise(map, file_length, MADV_WILLNEED); // No difference in performance if enabled
#endif
#ifdef WITH_MADV_SEQUENTIAL
madvise(map, file_length, MADV_SEQUENTIAL); // Massive performance degredation if enabled
#endif
const uint8_t *file_map_i = static_cast<const uint8_t *>(map);
const uint8_t *file_map_end = file_map_i + file_length;
size_t memcpy_size = MEMCPY_SIZE;
uint8_t *buffer = new uint8_t[memcpy_size];
while (file_map_i != file_map_end) {
size_t this_memcpy_size = std::min(memcpy_size, static_cast<std::size_t>(file_map_end - file_map_i));
memcpy(buffer, file_map_i, this_memcpy_size);
file_map_i += this_memcpy_size;
}
}
catch (const std::exception &e) {
std::cerr << "Caught exception: " << e.what() << std::endl;
}
return 0;
}