Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating elapsed time in a C program in milliseconds

Tags:

I want to calculate the time in milliseconds taken by the execution of some part of my program. I've been looking online, but there's not much info on this topic. Any of you know how to do this?

like image 477
user69514 Avatar asked Sep 23 '09 21:09

user69514


People also ask

How do you calculate elapsed time in C?

To get the elapsed time, we can get the time using clock() at the beginning, and at the end of the tasks, then subtract the values to get the differences. After that, we will divide the difference by CLOCK_PER_SEC (Number of clock ticks per second) to get the processor time.

How do you measure elapsed time?

In simple words, we can say that the amount of time that has passed between the beginning and the end of an event is called the elapsed time. We can determine this time by subtracting the end time and the start time. The formula to calculate the elapsed time is simply to subtract the hours and minutes separately.

Which of the following function is used to count the numbers of seconds elapsed?

time() :- This function is used to count the number of seconds elapsed since the epoch.


2 Answers

Best way to answer is with an example:

#include <sys/time.h> #include <stdlib.h> #include <stdio.h> #include <math.h>  /* Return 1 if the difference is negative, otherwise 0.  */ int timeval_subtract(struct timeval *result, struct timeval *t2, struct timeval *t1) {     long int diff = (t2->tv_usec + 1000000 * t2->tv_sec) - (t1->tv_usec + 1000000 * t1->tv_sec);     result->tv_sec = diff / 1000000;     result->tv_usec = diff % 1000000;      return (diff<0); }  void timeval_print(struct timeval *tv) {     char buffer[30];     time_t curtime;      printf("%ld.%06ld", tv->tv_sec, tv->tv_usec);     curtime = tv->tv_sec;     strftime(buffer, 30, "%m-%d-%Y  %T", localtime(&curtime));     printf(" = %s.%06ld\n", buffer, tv->tv_usec); }  int main() {     struct timeval tvBegin, tvEnd, tvDiff;      // begin     gettimeofday(&tvBegin, NULL);     timeval_print(&tvBegin);      // lengthy operation     int i,j;     for(i=0;i<999999L;++i) {         j=sqrt(i);     }      //end     gettimeofday(&tvEnd, NULL);     timeval_print(&tvEnd);      // diff     timeval_subtract(&tvDiff, &tvEnd, &tvBegin);     printf("%ld.%06ld\n", tvDiff.tv_sec, tvDiff.tv_usec);      return 0; } 
like image 66
Amro Avatar answered Oct 06 '22 08:10

Amro


Another option ( at least on some UNIX ) is clock_gettime and related functions. These allow access to various realtime clocks and you can select one of the higher resolution ones and throw away the resolution you don't need.

like image 21
Pete Kirkham Avatar answered Oct 06 '22 08:10

Pete Kirkham