Created
July 4, 2020 15:22
-
-
Save Alwinfy/e309ad32d67e9cd27ee310c8e43204d7 to your computer and use it in GitHub Desktop.
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 <stdlib.h> | |
#include <time.h> | |
void *alloc_2d_array(size_t size, int length, int width) { | |
int i; | |
size_t offset = length * sizeof(void *); | |
char **block = malloc(offset + size * length * width); | |
*block = (char *)(block + offset); | |
for (i = 1; i < length; i++) | |
block[i] = block[i - 1] + size * width; | |
return block; | |
} | |
#define N 0x2000 | |
#define SHUF(i) ((rand() & 0x1fff) ^ i) | |
int main() { | |
int *flat_arr = malloc(N * N * sizeof(int)); | |
int **ptr_arr = alloc_2d_array(sizeof(int), N, N); | |
int i, j, sum; | |
clock_t time; | |
printf("N = %d\n", N); | |
time = clock(); | |
for (i=0; i<N; i++) | |
for(j=0; j<N; j++) | |
sum += flat_arr[SHUF(i) * N + SHUF(j)]; | |
printf("Muladd time: %.4f\n", (double)(clock() - time) / CLOCKS_PER_SEC); | |
time = clock(); | |
for (i=0; i<N; i++) | |
for(j=0; j<N; j++) | |
sum += ptr_arr[SHUF(i)][SHUF(j)]; | |
printf("Twoptr time: %.4f\n", (double)(clock() - time) / CLOCKS_PER_SEC); | |
free(flat_arr); | |
free(ptr_arr); | |
exit(0); | |
} |
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
N = 8192 | |
Muladd time: 1.7231 | |
Twoptr time: 1.4388 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment