I am interested in at least an approximate answer to:
int n;
...
std::vector<void*> vectorOfPointers;
vectorOfPointers.reserve(n);
For up to which number n does the above mentioned program run in O(1) ?
Let us suppose that for a laptop running 32 bit Ubuntu with 3 gigabytes of memory, not running any other programs. Is it tens, thousands, millions? What information does one need to know to be able to asses such a question? Is there a way to find out without running any experiments?
I have never studied anything about operating systems but in my imagination, the operating system allocates memory in just 2 steps. It determines the pointer to start the chunk and the pointer of the end of the chunk. The situation can be more complicated because the system may have to tidy up in order to get a big enough chunk of memory. But if we suppose that the system runs just this one program, how can we estimate the time needed? Are there some other aspects to be considered, besides the fragmentation of memory?
EDIT:
sorry, I didn’t make my question clear. It is important to consider, that the vector is empty before calling reserve, so no copying of data is required.
From the C++ point of view, the code takes
O(1)time (it’s linear in the current size of the container, which in your case is always zero).Now, it seems that your question is really about the complexity of allocating
mbytes of memory. That, I am afraid, is unspecified.For further discussion, see Time complexity of memory allocation
To add to what’s already been said in the other question, there are several layers of complexity:
malloc()needs to maintain its internal data structures. The complexity of doing that is not specified, but one would hope thatmalloc(m)would not takeΘ(m)time. However, the complexity could well depend on other factors, such as memory fragmentation.malloc()may need to request additional memory from the OS. Here, it is not unreasonable to expect the OS to do something with every memory page it allocates (e.g. wipe it so you don’t see someone else’s confidential data). If this were to happen, the operation would indeed beΘ(m).