Any allocation of integers I try (varying the size of the array), the resulted time is still 0 NANOseconds.
Here is the code:
#include <iostream>
#include <chrono>
using namespace std;
using namespace chrono;
int* memory_allocation()
{
int *allocated_ints = new int[1000000];
return allocated_ints;
}
int main()
{
high_resolution_clock::time_point t0 = high_resolution_clock::now();
int *p = memory_allocation();
high_resolution_clock::time_point t1 = high_resolution_clock::now();
nanoseconds ns = duration_cast<nanoseconds>(t1 - t0);
std::cout << ns.count() << "ns\n";
delete[] p;
return 0;
}
Also, I tried encapsulating the memory allocation in a 1000000 million for loop, but the issue is that, I also have to deallocate it because of the heap space, resulting in also measuring the time for the 'delete' operation.
Is it really possible to be this small? If yes, is there any other way I can measure it?
Depending on your CPU speed, actual time resolution and some other platform specifics the allocation can be that fast - faster than your hi-res timer resolution.
As it has been mentioned here, it is not allocation of physical storage. The memory is not actually reserved for your process immediately after you call
new[]
. It is only allocation within your process virtual memory space. That is why it is fast.Depending on your platform, you may be able to use CPU hardware clock to measure the time more precisely. On x86 architecture there is RDTSC command which provides access to the CPU ticks counter. The problem with it is that modern CPUs change their clock speed depending on the load. Anyway, it is the most precise thing you could use. In C++ code it can be accessed through ASM block or through intrinsic functions like
__rdtsc()
. Here is the code specific to Visual Studio.Below is the result from my machine: