Time function

Hi. I have problem with time function. I try measure time need to sort array using bubble sort. I using float type but I cant get ant values after dot.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>

#define ARR_MAX 50000


void bubbleSort(int arr[], int n)
{
   int i, j,t;
   for (i = 0; i < n-1; i++)

      
       for (j = 0; j < n-i-1; j++)
           if (arr[j] > arr[j+1])
           {
               t = arr[j];
               arr[j] = arr[j+1];
               arr[j+1] = t;
           }

}
void print(int T[])
{
 int i;
 printf("\n[");
 for(i=0; i<ARR_MAX; i++)
 printf("%d ", T[i]);
 printf("]\n\n");
}

 void tab_random(int T[])
{
 int i;
 for(i = 0; i<ARR_MAX; i++)
 T[i] = rand() % 20;
}

int main()
{
 int i, arr[ARR_MAX];
 srand(time(NULL));
 time_t start,end;
 float how_long;
 tab_random(arr);
 //print(arr);
 //time(&start);
 start=time(NULL);
bubbleSort(arr,ARR_MAX);
 //time(&end);
 end=time(NULL);

 printf("\n Time: \n %.12f",difftime(end,start));
 //print(arr);

 return 0;
}
1
2
3
4
 clock_t start=clock();
 bubbleSort(arr,ARR_MAX);
 clock_t end=clock();
 printf("\n Time: \n %6.4f",(double)(end - start) / CLOCKS_PER_SEC);
time() usually has a resolution of one second.
To get better resolution you need to use clock() instead as lastchance shows.
These days it typically has at least microsecond resolution (i.e., CLOCKS_PER_SEC is at least a million).

To show the time in milliseconds:

 
printf("%.3f ms\n", (double)(end - start) / CLOCKS_PER_SEC * 1000);

Last edited on
Topic archived. No new replies allowed.