Which one is the best option and why? What is the difference between both options regarding the memory consumption and processing time?
The memory consumption and processing time has little difference.
The 2*3.14*r;
is a double
calculation and 2*pi*r
is a float
one and so the 2nd may take a tad less or more memory and time. Not because of constant vs. variable difference, but because of type differences and conversions.
Even if example code was corrected and used the same floating point types throughout, the difference is scant. Save your coding time for larger optimizations and let a well enabled compiler do low level optimizations. Is premature optimization really the root of all evil?
#define MY_PI 3.1415926535897932384626433832795
#define MY_PI_F 3.1415926535897932384626433832795f
#define MY_PI_LD 3.1415926535897932384626433832795L
float r = ...
float circumference = 2*MY_PI_F*r;
// or with double
double r = ...
double circumference = 2*MY_PI*r;
Note that OP's 2 codes are not functionally the same 39.4% of the time due to type changes with the double
calculation providing better answers.
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
#include <math.h>
int main() {
unsigned long fi = 0, di = 0;
float pi = 3.14;
for (float r = FLT_MAX; r > 0.0; r = nextafterf(r, 0.0)) {
fi++;
float circumference1 = 2*3.14*r;
float circumference2 = 2*pi*r;
if (circumference1 != circumference2) {
if (di == 0) printf("%.9g %.9g %.9g\n", r, circumference1, circumference2);
di++;
}
}
printf("Differences: %.1f%%\n", 100.0*di/fi);
}
When using float circumference1 = 2*3.14f*r;
, I found no functional difference, yet that is not a certainty in C.