Your question is Optimize a C Function. Take a moment with it on the right.
Talk me through your thinking if you like. When you're confident, submit your answer and I'll grade it like a real screen (7/10 or better passes).
You're a firmware engineer at Arm. This function runs on every sample batch coming off a sensor peripheral, byte-swapping and packing each 16-bit reading before handing the buffer to the application layer. It works, but it is eating far more of the CPU budget than a function this simple should.
typedef struct {
uint16_t reading;
uint8_t sensor_id;
} SensorSample;
void process_samples(SensorSample *samples, int count, uint8_t *output) {
for (int i = 0; i < get_sample_count(samples); i++) {
SensorSample *temp = malloc(sizeof(SensorSample));
temp->reading = samples[i].reading;
temp->sensor_id = samples[i].sensor_id;
uint16_t swapped = 0;
for (int bit = 0; bit < 16; bit++) {
if (bit < 8) {
swapped = swapped | (((temp->reading >> bit) & 1) << (bit + 8));
} else {
swapped = swapped | (((temp->reading >> bit) & 1) << (bit - 8));
}
}
output[i * 3] = (uint8_t)(swapped >> 8);
output[i * 3 + 1] = (uint8_t)(swapped & 0xFF);
output[i * 3 + 2] = temp->sensor_id;
free(temp);
}
}
How can the following function in C be optimized? Explain what you would change and why, for a function that runs on every sample batch on a resource-constrained device.