How to test efficiency of different algorithms, for example, sorting algorithms? I try it with clock_gettime
. Is it accurate? Are there any ways to solve this problem?
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
/* compute interval: end - start */
struct timespec diff(struct timespec start, struct timespec end);
/* tested algorithm, just an example. Print 10000 lines "hello" */
void testFunc(void);
int main(void)
{
struct timespec start;
struct timespec end;
struct timespec interval ;
clock_gettime(CLOCK_REALTIME, &start);
/* call the tested algorithm */
testFunc();
clock_gettime(CLOCK_REALTIME, &end);
interval = diff(start, end);
printf("%lld.%.9ld(seconds)\n", (long long)interval.tv_sec, interval.tv_nsec);
return 0;
}
/* compute interval: end - start */
struct timespec diff(struct timespec start, struct timespec end)
{
struct timespec temp;
if ((end.tv_nsec - start.tv_nsec) < 0) {
temp.tv_sec = end.tv_sec - start.tv_sec - 1;
temp.tv_nsec = 1000000000 + end.tv_nsec - start.tv_nsec;
}
else {
temp.tv_sec = end.tv_sec - start.tv_sec;
temp.tv_nsec = end.tv_nsec - start.tv_nsec;
}
return temp;
}
/* tested algorithm, just an example. Print 10000 lines "hello" */
void testFunc(void)
{
int i;
for (i = 0; i < 10000; i++) {
printf("hello\n");
}
}