Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*******************************************************************************
- test_square
- Timed loops to compare the floating point calculation using f * f directly,
- as an inline and regular function compared to using the intrinsic math pow()
- function.
- *******************************************************************************/
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #include <math.h>
- #define LOOP 10000
- #define SIZE 10000
- __attribute__((always_inline))
- inline static float inline_sq(float n) { return n * n; }
- float square(float n) { return n * n; }
- int main(int argc, char *argv[])
- {
- float reals[SIZE];
- float result = 0.0;
- double dummy;
- clock_t start, stop;
- printf("%s\t%'dx%'d\n", argv[0], LOOP, SIZE);
- // random array of floats 1 & 10
- for (int i = 0; i < SIZE; i++)
- reals[i] = 1 + 9 * (float) rand() / (float) RAND_MAX;
- // test multiplication
- start = clock();
- dummy = 0;
- for (int t = 0; t < LOOP; t++) {
- result = 0;
- for (int i = 0; i < SIZE; i++) {
- float f = reals[i];
- result += f * f;
- }
- dummy += result;
- }
- stop = clock();
- printf("f * f\t\t%0.6f\t%0.6f\n", (float) (stop - start) / (float) CLOCKS_PER_SEC, dummy);
- // test function inline
- start = clock();
- dummy = 0;
- for (int t = 0; t < LOOP; t++) {
- result = 0;
- for (int i = 0; i < SIZE; i++) {
- float f = reals[i];
- result += inline_sq(f);
- }
- dummy += result;
- }
- stop = clock();
- printf("inline_sq(f)\t%0.6f\t%0.6f\n", (float) (stop - start) / (float) CLOCKS_PER_SEC, dummy);
- // test function square
- start = clock();
- dummy = 0;
- for (int t = 0; t < LOOP; t++) {
- result = 0;
- for (int i = 0; i < SIZE; i++) {
- float f = reals[i];
- result += square(f);
- }
- dummy += result;
- }
- stop = clock();
- printf("square(f, 2)\t%0.6f\t%0.6f\n", (float) (stop - start) / (float) CLOCKS_PER_SEC, dummy);
- // test pow()
- start = clock();
- dummy = 0;
- for (int t = 0; t < LOOP; t++) {
- result = 0;
- for (int i = 0; i < SIZE; i++) {
- float f = reals[i];
- result += pow(f, 2);
- }
- dummy += result;
- }
- stop = clock();
- printf("pow(f, 2)\t%0.6f\t%0.6f\n", (float) (stop - start) / (float) CLOCKS_PER_SEC, dummy);
- } /* main */
Add Comment
Please, Sign In to add comment