[ create a new paste ] login | about

Link: http://codepad.org/mcj1jk0i    [ raw code | fork ]

C, pasted on Feb 6:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>

int main()
{
    // Let's allocate a 2d array with 10Mb data.
    int n = 1000;
    char (*a)[n] = malloc((sizeof *a) * n); // Note that *a is expanded to a[n]
    
    struct timeval start, end;
    time_t time1_us, time1_s, time2_us, time2_s;
    int i,j;
    
    // Access a[i][j]
    gettimeofday(&start, NULL); 
    for (i=0; i<n; i++)
    {
        for (j=0; j<n; j++)
        {
            a[i][j] = 4;
        }
    }
    gettimeofday(&end, NULL); 
    
    time1_us = end.tv_usec - start.tv_usec;
    time1_s = end.tv_sec - start.tv_sec;
    
    // Access a[j][i]
    gettimeofday(&start, NULL);
    for (i=0; i<n; i++)
    {
        for (j=0; j<n; j++)
        {
            a[j][i] = 4;
        }
    }
    gettimeofday(&end, NULL);
    
    time2_us = end.tv_usec - start.tv_usec;
    time2_s = end.tv_sec - start.tv_sec;
    
    printf("Accessing a[i][j] took: %li sec and %li usec\n", time1_s, time1_us);
    printf("Accessing a[j][i] took: %li sec and %li usec\n", time2_s, time2_us);
    
    free(a);
    return 0;
}

--
The numbers I get on my MacBook Pro (Intel Core2 Penryn), DDR3 @1067Mhz:

Accessing a[i][j] took: 0 sec and 4898 usec
Accessing a[j][i] took: 0 sec and 9391 usec


Create a new paste based on this one


Comments: