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
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).
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.
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].
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.
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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With