Allocate and acccess 512MB of memory using 512 1MB VirtualAllocs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdint.h> | |
| #include <windows.h> | |
| static int64_t timer() | |
| { | |
| LARGE_INTEGER li; | |
| QueryPerformanceCounter(&li); | |
| return li.QuadPart; | |
| } | |
| static int64_t timer_freq() | |
| { | |
| LARGE_INTEGER li; | |
| QueryPerformanceFrequency(&li); | |
| return li.QuadPart; | |
| } | |
| volatile uint32_t g_sink; | |
| static const int size = 512 << 20; | |
| #if 1 | |
| static const int num_allocs = 512; | |
| static unsigned char *allocs[num_allocs]; | |
| #else | |
| static const int num_allocs = 1; | |
| static unsigned char global_buf[size]; | |
| static unsigned char *allocs[1] = { global_buf }; | |
| #endif | |
| static void time_it() | |
| { | |
| int64_t start = timer(); | |
| int size_per_alloc = size / num_allocs; | |
| for (int i = 0; i < num_allocs; i++) | |
| { | |
| if (!allocs[i]) | |
| allocs[i] = (unsigned char *)VirtualAlloc(NULL, size_per_alloc, MEM_COMMIT, PAGE_READWRITE); | |
| unsigned char *p = allocs[i]; | |
| // access every cache line once | |
| for (int i = 0; i < size_per_alloc; i += 64) | |
| g_sink += p[i]; | |
| } | |
| int64_t end = timer(); | |
| int64_t freq = timer_freq(); | |
| double duration = 1.0 * (end - start) / freq; | |
| printf("%.1fms (%.2f GB/s)\n", 1000.0 * duration, size / (1048576.0 * 1024.0 * duration)); | |
| } | |
| int main() | |
| { | |
| for (int run = 0; run < 5; run++) | |
| { | |
| printf("run=%d ", run); | |
| time_it(); | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment