Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <stdint.h>
- #include <math.h>
- #include <time.h>
- #define NUM_TESTLOOPS 10000
- #define NUM_INNERLOOPS 10000
- #define PRECISION 1024 // ~ 3 digits
- // floating/fixed point conversion
- inline int32_t FIXED(float x) { return x * PRECISION; }
- inline float FLOAT(int32_t x) { return (float)x / PRECISION; }
- // testing values
- float value[4];
- int32_t ivalue[4];
- // timing
- float _time() { return (float)clock() / CLOCKS_PER_SEC; }
- // perform add, subtract, divide, and multiply with floats
- float op_floating(float v)
- {
- int x;
- // do work with floats
- for(x = 0; x < NUM_INNERLOOPS; x++)
- {
- v += value[0];
- v -= value[1];
- v *= value[2];
- v /= value[3];
- }
- return v;
- }
- // perform add, sub, mul, div, return converted to float
- int op_fixed(int iv)
- {
- int x;
- // do work with ints
- for(x = 0; x < NUM_INNERLOOPS; x++)
- {
- iv += ivalue[0];
- iv -= ivalue[1];
- iv = ((int64_t)iv*ivalue[2])/PRECISION;
- iv = ((int64_t)iv*PRECISION)/ivalue[3];
- }
- return iv;
- }
- int main(int argc, char **argv)
- {
- int x, iresult = 0;
- float t1, t2, result = 0;
- printf("------------------------------------------\n");
- printf("Simplistic test: fixed vs floating point arithmetic\n");
- printf("------------------------------------------\n\n");
- // generate work values
- unsigned seed = time(0); // N.B. not all seed values give valid results
- srand(seed);
- printf("Seed: %x\n", seed);
- float start = 100*((float)rand()/RAND_MAX);
- int istart = FIXED(start);
- printf("Start: %f\tVals:", start);
- for(x = 0; x < 4; x++)
- {
- value[x] = 5*((float)rand()/RAND_MAX);
- ivalue[x] = FIXED(value[x]);
- printf(" %3.2f",value[x]);
- }
- // timed floating point arithmetic test
- printf("\n\nbeginning timed floating-point work\n");
- t1 = _time();
- // do expensive floating-point work
- for(x = 0; x < NUM_TESTLOOPS; x++)
- result += op_floating(start);
- t1 = _time() - t1;
- float fresult = op_floating(start);
- printf("floating-point test time: %2.3fs\nresult = %f\n\n", t1, fresult);
- // timed fixed-point arithmetic test
- printf("beginning timed fixed-point work\n");
- t2 = _time();
- // do expensive fixed-point work
- for(x = 0; x < NUM_TESTLOOPS; x++)
- iresult += op_fixed(istart);
- t2 = _time() - t2;
- float firesult = FLOAT(op_fixed(istart));
- printf("fixed-point test time: %2.3fs\nresult = %f\n\n", t2, firesult);
- double relativeError = fabs(fresult/(double)firesult - 1.0);
- printf("relative error: %f\n", relativeError);
- printf("relative time: %f\n", t2/t1);
- return result-iresult;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement