/* link with -lm */
#define _XOPEN_SOURCE 500
#include <stdio.h>
#include <math.h>
#include <complex.h>
#include <time.h>
double mycos (double rads) {
double perc = fabs(rads / M_PI);
/* perc may be zero. C declares 0 ** 0 == NaN.
** use the same point on the next cycle instead.
*/
perc = perc ? perc : 2;
return pow(perc, perc) * creal(cpow(-perc, -perc));
}
double clock_diff (struct timespec *b, struct timespec *a) {
return a->tv_sec - b->tv_sec
+ (float)(a->tv_nsec - b->tv_nsec) / 1000000000;
}
int main (void) {
struct timespec before, after;
clock_gettime(CLOCK_MONOTONIC_RAW, &before);
for (float i = 0; i < 2 * M_PI; i += (float)M_PI / 1000000) cos(i);
clock_gettime(CLOCK_MONOTONIC_RAW, &after);
float time_a = clock_diff(&before, &after);
printf("cos() took %f seconds\n", time_a);
clock_gettime(CLOCK_MONOTONIC_RAW, &before);
for (float i = 0; i < 2 * M_PI; i += (float)M_PI / 1000000) mycos(i);
clock_gettime(CLOCK_MONOTONIC_RAW, &after);
float time_b = clock_diff(&before, &after);
printf("mycos() took %f seconds\n", time_b);
printf("mycos() takes approximately %.15f times longer to run than cos()\n",
time_b / time_a
);
puts("sanity:");
for (float i = 0; i < 2 * M_PI; i += 1) {
printf("cos (%.15f):\t%+.15f\n", i, cos(i));
printf("mycos(%.15f):\t%+.15f\n", i, mycos(i));
}
return 0;
}