c - How to measure the execution time in micro seconds? -


this question has answer here:

i have written following code measure time of sorting data. getting weird results, negative time in cases , not getting consistent result same data set(i understand won't same). please let me know wrong or how can measure time properly.

#include<stdio.h> #include<sys/time.h>  void bubble(int a[],int n) {     int i,j,flag,temp;     for(i=0;i<n-1;i++)     {         flag=0;         for(j=0;j<n-i-1;j++)         {             if(a[j]>a[j+1])             {                 flag=1;                 a[j]=a[j]+a[j+1];                 a[j+1]=a[j]-a[j+1];                 a[j]=a[j]-a[j+1];             }         }         if(flag==0)             break;     } }  int main() {     int n,a[100000],i;     printf("enter size of array:");     scanf("%d",&n);     for(i=0;i<n;i++)         a[i]=rand()%100000;     //average case         //a[i]=i;               //best case         //a[i]=n-1-i;           //worst case     /*     printf("the unsorted array is:\n");     for(i=0;i<n;i++)         printf("%d ",a[i]);     printf("\n\n");     */      int st,et;     struct timezone tz;     struct timeval tv;     gettimeofday(&tv,null);     st=tv.tv_usec;     bubble(a,n);     gettimeofday(&tv,null);     et=tv.tv_usec;     printf("sorting time: %d micro seconds\n",et-st);     /*     printf("\nthe sorted array is:\n");     for(i=0;i<n;i++)         printf("%d ",a[i]);     printf("\n");     */     return 0; } 

the struct timeval populated gettimeofday defined follows:

struct timeval {     time_t      tv_sec;     /* seconds */     suseconds_t tv_usec;    /* microseconds */ }; 

the tv_sec , tv_usec fields together contains seconds , microseconds since epoch. microseconds part contains fractional seconds, i.e. value 0 999999.

you need subtract seconds and microseconds.

struct timeval st, et;  gettimeofday(&st,null); bubble(a,n); gettimeofday(&et,null);  int elapsed = ((et.tv_sec - st.tv_sec) * 1000000) + (et.tv_usec - st.tv_usec) printf("sorting time: %d micro seconds\n",elapsed); 

if total run time short, can perform multiple runs , average them out:

struct timeval st, et; int i, num_runs = 5;  gettimeofday(&st,null); (i=0; i<num_runs; i++) {     bubble(a,n); } gettimeofday(&et,null);  int elapsed = (((et.tv_sec - st.tv_sec) * 1000000) + (et.tv_usec - st.tv_usec)) / num_runs; 

Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -