What is the key difference between the following two C functions?
— ADVERTISMENT—
—Advertise Here—
#define VOLTS_FULL_SCALE 5.000
#define KPA_PER_VOLT 100.0
#define KPA_THRESHOLD 200.0
/* adc_reading is a value between 0 and 1
*/
bool test_pressure (float adc_reading)
{
float voltage = adc_reading * VOLTS_FULL_SCALE;
float pressure = voltage * KPA_PER_VOLT;
return pressure > KPA_THRESHOLD;
}
bool test_pressure2 (float adc_reading)
{
float voltage_threshold = KPA_THRESHOLD / KPA_PER_VOLT;
float adc_threshold = voltage_threshold / VOLTS_FULL_SCALE;
return adc_reading > adc_threshold;
}
The first function, test_pressure(), converts the ADC reading to engineering units before making the threshold comparison. This is a direct, obvious way to implement such a function.
The first function, test_pressure2(), converts the threshold value to an equivalent ADC reading, so that the two can be compared directly.
— ADVERTISMENT—
—Advertise Here—
The key difference is in performance. The first function requires that arithmetic be done on each reading before making the comparison. However, the calculations in the second function can all be performed at compile time, which means that the only run-time operation is the comparison itself.