跳到正文

个人记录

mmap快速读入

wyr_约 3 分钟
原文
文章信息与版本

文章信息

发布
2022年2月16日
收录
2025年12月12日
更新
2026年11月14日
篇幅
约 3 分钟
获赞
1

版本

  1. v1当前

简单实现

C
#include<sys/mman.h>//mmap头文件
#include<fcntl.h>//open头文件
#include<cstdio>//stdio头文件
char *buf;
void stdin_mmap(){
	buf=(char*)mmap(nullptr,
	                1<<26,
	                PROT_READ,
	                MAP_PRIVATE,
	                fileno(stdin),
	                0);
}
void file_mmap(const char *name){
	buf=(char*)mmap(nullptr,
	                1<<26,
	                PROT_READ,
	                MAP_PRIVATE,
	                open(name,O_RDONLY),
	                0);
}
char getChar(){
	return *(buf++);
}

如果你用这段代码套上快读模版,并且读入这个生成器所生成的262144个整数,你的程序将会收到SIGSEGV或SIGBUS信号。这是由于文件大小是内存页大小的整数倍时,读取文件尾后面的第一个字符就会超出mmap所映射的内存区域。

规范化实现:

(检测读入文件的大小,防止缓冲区指针超出文件尾部导致程序异常终止)

(比上面那个慢,但所用时间差不超过20ms)

C++
#include<cstdio>
#include<sys/mman.h>
#include<sys/stat.h>
#include<fcntl.h>
class Istream{
private:
	char *buf,*p,*tail;
public:
	Istream(const char *name){
		int fd=open(name,O_RDONLY);
		struct stat s;
		fstat(fd,&s);
		p=buf=reinterpret_cast<char*>(mmap(NULL,s.st_size,PROT_READ,MAP_PRIVATE,fd,0));
		tail=buf+s.st_size;
	}
	Istream(){
		int fd=fileno(stdin);
		struct stat s;
		fstat(fd,&s);
		p=buf=reinterpret_cast<char*>(mmap(NULL,s.st_size,PROT_READ,MAP_PRIVATE,fd,0));
		tail=buf+s.st_size;
	}
	char getchar(){
		return p==tail?-1:*p++;
	}
};

附 录

mmap函数的定义:

C
void *mmap(void *addr, size_t len, int prot, int flags, int fd, off_t offset);

参考资料

  1. 认真分析mmap:是什么 为什么 怎么用 - 胡潇 - 博客园
  2. OI 中有哪些常数优化技巧? - xehoth的回答 - 知乎
原文