Will the automatic memory allocation faster than dynamic memory allocation?

I tried to make test, but failed.

1
2
3
4
5
6
7
8
9
10
11
clock_t begin = clock();
int arr[100000];
clock_t end = clock();
cout << (end - begin) << endl;

begin = clock();
int* p = new int[100000];
end = clock();
cout << (end - begin) << endl;

delete[] p;



0
0
Try using the time facilities provided by C++11:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <chrono>
#include <iostream>

int main() {
    using namespace std::chrono;
    
    {
        auto p = high_resolution_clock::now();
        int arr[1000000];
        nanoseconds t = high_resolution_clock::now() - p;
        std::cout << "Static: " << t.count() << " nanoseconds.\n";
    }
    
    {
        auto p = high_resolution_clock::now();
        int* arr = new int[1000000];
        nanoseconds t = high_resolution_clock::now() - p;
        std::cout << "Dynamic: " << t.count() << " nanoseconds.\n";
    }
    
    return 0;
}
Static: 1499 nanoseconds.
Dynamic: 92698 nanoseconds.

http://coliru.stacked-crooked.com/a/b99a21dde5ec23e9
Last edited on
thank you, NT3.
But By using your way, I still get two 0 s with my compiler. My compiler is VS2013.
Last edited on
FOr windows you can use QueryPerformanceCounter function
http://msdn.microsoft.com/en-us/library/ms644904.aspx

Alternatively you can use rdtsc processor command to querry current tick count:
http://coliru.stacked-crooked.com/a/79bfb47da5f41a3d
(Warning! Tis code is GCC only. ASM inserts are usually unportable)

Automatic memory allocation is usually just decreasing single value in processor register: all stack memory space is already preallocated during program startup (also that means that usually it cannot be increased in runtime and program can crash if it exhaust all that memory)
Dynamic allocation usually requires call to system memory manager. That is why it is slower.
Last edited on
Topic archived. No new replies allowed.