Skip to content

Instantly share code, notes, and snippets.

@zeta709
Last active December 20, 2015 22:49
Show Gist options
  • Select an option

  • Save zeta709/6208314 to your computer and use it in GitHub Desktop.

Select an option

Save zeta709/6208314 to your computer and use it in GitHub Desktop.
Measuring execution time of a function.
#include <stdio.h>
volatile int tmp;
static const int N = 123456789;
/* Linux method #0: use gettimeofday() (obsolete?)
*/
#include <sys/time.h>
// timeradd, timersub, etc. macros are _BSD_SOURCE.
// Those will be defined only if the symbol __USE_BSD is defined.
#ifndef timersub
#define timersub(a, b, result) \
do { \
(result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
(result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \
if ((result)->tv_usec < 0) { \
--(result)->tv_sec; \
(result)->tv_usec += 1000000; \
} \
} while (0)
#endif // timersub
void linux_method0(void)
{
struct timeval time0, time1, time_diff;
// start time
gettimeofday(&time0, NULL);
// do something
int i;
for (i = 0; i < N; ++i) {
tmp = i;
}
// finish time
gettimeofday(&time1, NULL);
// print elapsed time
timersub(&time1, &time0, &time_diff);
printf("Elapsed time: %ld.%06ld s\n",
time_diff.tv_sec, time_diff.tv_usec);
}
/* Linux method #1: use clock_gettime()
* Compile with -std=gnu99
* Link with -lrt (glibc <2.17)
*/
#include <time.h>
#define timespec_sub(a, b, result) \
do { \
(result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \
(result)->tv_nsec = (a)->tv_nsec - (b)->tv_nsec; \
if ((result)->tv_nsec < 0) { \
--(result)->tv_sec; \
(result)->tv_nsec += 1000000000; \
} \
} while (0)
void linux_method1(void)
{
struct timespec time0, time1, time_diff;
// start time
clock_gettime(CLOCK_REALTIME, &time0);
// do something
int i;
for (i = 0; i < N; ++i) {
tmp = i;
}
// finish time
clock_gettime(CLOCK_REALTIME, &time1);
// print elapsed time
timespec_sub(&time1, &time0, &time_diff);
printf("Elapsed time: %ld.%09ld s\n",
time_diff.tv_sec, time_diff.tv_nsec);
}
/* Windows method #0
*/
#include <windows.h>
void windows_method0(void)
{
LARGE_INTEGER li;
__int64 CounterStart = 0;
if (!QueryPerformanceFrequency(&li))
printf("QueryPerformanceFrequency failed\n");
double PCFreq = (double) li.QuadPart;
// start time
QueryPerformanceCounter(&li);
CounterStart = li.QuadPart;
// do something
int i;
for (i = 0; i < N; ++i) {
tmp = i;
}
// finish time
QueryPerformanceCounter(&li);
printf("Elapsed time: %.6f s\n",
((double) (li.QuadPart - CounterStart)) / PCFreq);
}
int main()
{
linux_method0();
linux_method1();
windows_method0();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment