Register Variable Test
C
Hard
2 views
Problem Description
Use a normal variable and a register variable in a loop. Increment both by 1 million. Measure the time difference (practical experiment).
Official Solution
#include <stdio.h>
#include <time.h>
int main() {
int i;
int normal = 0;
register int reg = 0;
clock_t start, end;
double time_normal, time_register;
/* ---- Normal variable loop ---- */
start = clock();
for (i = 0; i < 1000000; i++) {
normal++;
}
end = clock();
time_normal = (double)(end - start) / CLOCKS_PER_SEC;
/* ---- Register variable loop ---- */
start = clock();
for (i = 0; i < 1000000; i++) {
reg++;
}
end = clock();
time_register = (double)(end - start) / CLOCKS_PER_SEC;
printf("Normal variable value = %dn", normal);
printf("Register variable value = %dnn", reg);
printf("Time taken by normal variable = %f secondsn", time_normal);
printf("Time taken by register variable = %f secondsn", time_register);
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!