c++ - Accessing unallocated page -


in concept of virtual memory, physical page frame allocated when corresponding page used in virtual space.

i wonder when such allocation takes place.

i tried reference addresses randomly chosen, of time, gives me segmentation fault. guess pages marked non-using, , reading page not enough force os allocate me physical page frame. (i tried gdb)

the os handle this. see in action need instrument or apply debugger os kernel code, concept may seen by:

int *p = new int[1000000]; 

this allocate approximately 4mb (1000 pages) of memory, far none of them have been used, none of "physically allocated" (but perhaps first 1 has, since used store metadata allocation)

p[2048] = 42;  

now, os take page-fault 8192 bytes allocation, , once complete, value 42 can written page.

running gdb not show this. other fact it's slower writing "committed" physical page, it's unnoticeable - try out writing 1 element in every 4k in 100mb of data, or first 250000 entries in same 100mb - , writing second time. both faster esecond time, page-faults not happening second time, second time in first case noticeably faster.

an example:

#include <iostream> #include <chrono> #include <functional> #include <memory>  void measure(const std::string& test, std::function<void()> function) {     auto start_time = std::chrono::high_resolution_clock::now();      function();      auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::high_resolution_clock::now() - start_time);     std::cout<<test<<" "<<static_cast<double>(duration.count()) * 0.000001<<" ms"<<std::endl; }  const int nwrites = 1024*1024; const int pagestep = 1024; const int nints = nwrites*pagestep; /* 1024m * sizeof(int) = 4gb */  int main() {     std::unique_ptr<int[]> p(new int [nints]);      measure("every int", [&p](){ for(int = 0; < nwrites; i++) p[i] = i; });     measure("every 4kb", [&p](){ for(int = 0; < nwrites; i++) p[i*pagestep] = i; });         measure("every int", [&p](){ for(int = 0; < nwrites; i++) p[i] = i; }); measure("every 4kb", [&p](){ for(int = 0; < nwrites; i++) p[i*pagestep] = i; }); } 

gives this:

every int 10.3651 ms every 4kb 1856.2 ms every int 2.4179 ms every 4kb 84.1603 ms 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -