Successive calls to mmap, any caching?
c++, linux, memory, mmap
Solution
Assuming you're talking about something *NIX-ish, there's probably a page cache, whose job is precisely to cache this sort of data to get this speedup. Unless something else came along between calls to evict those pages from the cache, they'll still be there.
So, the first call potentially has to:
- allocate pages
- map the pages into your process address space
- copy the data from those pages into your vector (possibly faulting the data from disk as it goes)
the second call probably finds the pages still in the cache, and only has to:
- map the pages into your process address space
- copy the data from those pages into your vector (they're pre-faulted this time, so it's a simple memory operation)
In fact, I've skipped a step: the open/fstat step in your comment is probably also accelerated, via the inode cache.
Problem
I read in a vector as in: ``` int readBytes(string filename, vector<uint32_t> &v) { // fstat file, get filesize, etc. uint32_t *filebuf = (uint32_t*)mmap(0,filesize,PROT_READ, MAP_FILE|MAP_PRIVATE, fhand,0); v = std::vector<uint32_t>(filebuf,filebuf+numrecords); munmap(filebuf, filesize); } ``` in main() I have two successive calls (purely as a test): ``` vector<uint32_t> v(10000); readBytes(filename, v); readBytes(filename, v); // ... ``` The second call almost always gives a faster clock time: ``` Profile time [1st call]: 0.000214141 sec Profile time [2nd call]: 0.000094109 sec ``` A look at the system calls indicates the memory chunks are differend: ``` mmap(NULL, 40000, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7fe843ac8000 mmap(NULL, 40000, PROT_READ, MAP_PRIVATE, 4, 0) = 0x7fe843ac7000 ``` Why is the second call faster? Coincidence? What, if anything, is cached?