1

given the code below

#include<time.h> 
#include <stdio.h>
#include <stdlib.h>

void firstSequence()
{
    int columns = 999999;
    int rows = 400000;
    int **matrix;
    int j;
    int counter = 0;
    matrix = (int **)malloc(columns*sizeof(int*));  
    for(j=0;j<columns;j++)
    {
            matrix[j]=(int*)malloc(rows*sizeof(int));
    }
    for(counter = 1;counter < columns; counter ++)
    {
        free(matrix[counter]);
    }
}

void secondSequence()
{
    int columns = 111;
    int rows = 600000;
    int **matrix;
    int j;
    matrix = (int **)malloc(columns*sizeof(int*));  
    for(j=0;j<columns;j++)
    {
              matrix[j]=(int*)malloc(rows*sizeof(int));
    }
}


int main()
{
    long t1;
    long t2;
    long diff;
    t1 = clock(); 
    firstSequence();
    t2 = clock();

    diff = (t2-t1) * 1000.0 / CLOCKS_PER_SEC;
    printf("%f",t2);

    t1 = clock(); 
    secondSequence();
    t2 = clock();
    diff = (t2-t1) * 1000.0 / CLOCKS_PER_SEC;  
    printf("%f",diff);



    return(0);
}

I need to be able to see how long it takes for both sequence one and sequence two to run. However both times I get 0 as the time elapsed. From looking online I have seen that this can be an issue but I do not how to fix the issue

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
Robert Spratlin
  • 305
  • 3
  • 5
  • 8

2 Answers2

2

You display the time incorrectly, so even if your functions take more than 0ms the call to printf() invokes undefined behaviour.

printf("%f",diff);

%f is used to display doubles. You probably want to use %ld.

If your functions really do take 0 ms to execute then a simple method to calculate the time for one call to the function is to call it multiple times, evough to be measurable, and then take the average of the total time elapsed.

tinman
  • 6,348
  • 1
  • 30
  • 43
0

clock is not the suitable function for calculating the time a program used.

You should use clock_gettime instead. detail explain about clock_gettime

Simple usage:

struct timespec start, end;
clock_gettime(CLOCK_REALTIME, &start);
for(int i = 0; i < 10000; i++) {
     f1();
}
clock_gettime(CLOCK_REALTIME, &end);
cout <<"time elapsed = " << (double)((end.tv_sec - start.tv_sec)*1000000 + end.tv_nsec - start.tv_nsec) << endl;

PS: when you are compiling on linux, remember using the -lrt.

Community
  • 1
  • 1
luoluo
  • 5,353
  • 3
  • 30
  • 41