I would like to measure time in C, and I am having a tough time figuring it out, all I want is something like this:
Any help would be appreciated.
(I am compiling in windows using mingw)
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.
Response time measure is the time from the submission of a request until the first output is produced.
time(NULL) returns the number of seconds elapsed since 01/01/1970 at 00:00 (the Epoch). So the difference between the two values is the number of seconds your processing took. int t0 = time(NULL); doSomthing(); doSomthingLong(); int t1 = time(NULL); printf ("time = %d secs\n", t1 - t0);
High resolution timers that provide a resolution of 1 microsecond are system-specific, so you will have to use different methods to achieve this on different OS platforms. You may be interested in checking out the following article, which implements a cross-platform C++ timer class based on the functions described below:
Windows
The Windows API provides extremely high resolution timer functions: QueryPerformanceCounter()
, which returns the current elapsed ticks, and QueryPerformanceFrequency()
, which returns the number of ticks per second.
Example:
#include <stdio.h> #include <windows.h> // for Windows APIs int main(void) { LARGE_INTEGER frequency; // ticks per second LARGE_INTEGER t1, t2; // ticks double elapsedTime; // get ticks per second QueryPerformanceFrequency(&frequency); // start timer QueryPerformanceCounter(&t1); // do something // ... // stop timer QueryPerformanceCounter(&t2); // compute and print the elapsed time in millisec elapsedTime = (t2.QuadPart - t1.QuadPart) * 1000.0 / frequency.QuadPart; printf("%f ms.\n", elapsedTime); }
Linux, Unix, and Mac
For Unix or Linux based system, you can use gettimeofday()
. This function is declared in "sys/time.h".
Example:
#include <stdio.h> #include <sys/time.h> // for gettimeofday() int main(void) { struct timeval t1, t2; double elapsedTime; // start timer gettimeofday(&t1, NULL); // do something // ... // stop timer gettimeofday(&t2, NULL); // compute and print the elapsed time in millisec elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0; // sec to ms elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0; // us to ms printf("%f ms.\n", elapsedTime); }
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