Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - gettimeofday for computing time?

Tags:

c

do you know how to use gettimeofday for measuring computing time? I can measure one time by this code:

  char buffer[30];   struct timeval tv;    time_t curtime;     gettimeofday(&tv, NULL);   curtime=tv.tv_sec;   strftime(buffer,30,"%m-%d-%Y  %T.",localtime(&curtime));  printf("%s%ld\n",buffer,tv.tv_usec); 

This one is made before computing, second one after. But do you know how to subtracts it?

I need result in miliseconds

like image 585
Waypoint Avatar asked Mar 19 '11 14:03

Waypoint


People also ask

What does gettimeofday do in c?

The gettimeofday() function gets the system's clock time. The current time is expressed in elapsed seconds and microseconds since 00:00:00, January 1, 1970 (Unix Epoch).

How to use timeval in c?

If you remember the select function arguments in socket,the last argument, timeout, points to a structure that must be initialized unless a NULL pointer is provided instead. Listing 11.3 shows the definition of the timeval structure.

What is Suseconds_t?

The type useconds_t shall be an unsigned integer type capable of storing values at least in the range [0, 1000000]. The type suseconds_t shall be a signed integer type capable of storing values at least in the range [-1, 1000000].

What is Timeval?

Data Type: struct timeval. struct timeval is an older type for representing a simple calendar time, or an elapsed time, with sub-second resolution. It is almost the same as struct timespec , but provides only microsecond resolution. It is declared in sys/time.h and has the following members: time_t tv_sec.


2 Answers

To subtract timevals:

gettimeofday(&t0, 0); /* ... */ gettimeofday(&t1, 0); long elapsed = (t1.tv_sec-t0.tv_sec)*1000000 + t1.tv_usec-t0.tv_usec; 

This is assuming you'll be working with intervals shorter than ~2000 seconds, at which point the arithmetic may overflow depending on the types used. If you need to work with longer intervals just change the last line to:

long long elapsed = (t1.tv_sec-t0.tv_sec)*1000000LL + t1.tv_usec-t0.tv_usec; 
like image 161
R.. GitHub STOP HELPING ICE Avatar answered Oct 02 '22 17:10

R.. GitHub STOP HELPING ICE


If you want to measure code efficiency, or in any other way measure time intervals, the following will be easier:

#include <time.h>  int main() {    clock_t start = clock();    //... do work here    clock_t end = clock();    double time_elapsed_in_seconds = (end - start)/(double)CLOCKS_PER_SEC;    return 0; } 

hth

like image 34
Armen Tsirunyan Avatar answered Oct 02 '22 16:10

Armen Tsirunyan