Why does using the "register" keyword makes my code faster?

Viewed 42

I am learning/re-learning C, and I've learnt about the register keyword. On many websites, people said it is recommended to not be used, or even useless. The book I am using says it is useful in for-loops, then I tried without the keyword:

#include <stdio.h>
#include <time.h>

int main() {
    int count = 1;

    clock_t start = clock();
    while(count != 0) {
        count++;
    }
    clock_t stop = clock();
    double time = (double)(stop - start);

    printf("%f", time);

    return 0;
}

and, then with it:

[..] register int count = 1; [...]

Compiling the source code with GCC, I have seen that using register made the program around 5x faster. Executables:

  1. https://drive.google.com/file/d/1IQHmmNSo6wbAXhl8cBzKjzXLPmvbseQB/view?usp=sharing
  2. https://drive.google.com/file/d/1MtV_eRoe-WDWNKT48yk1T3jadIm6SuOD/view?usp=sharing

Hence, my question, is there something wrong with me (e.g. my GCC) or is the register keyword actually useful?

1 Answers

Whenever a variable is created in a program, it can be either stored in memory(RAM) or in CPU register. And of course accessing the variable from CPU registers is much faster than to access it from RAM. To get your variable stored in CPU register, 'register' keyword is used while declaring the variable. To store it in memory, which is also default store type in C, one can use 'auto' keyword. Although accessing variables from CPU registers is much faster, it is recommended to not to use unless necesarry because the number of CPU registers are limited. Even though one declares the storage class of a variable as register, we cannot say for sure that the value of variable would be stored in a CPU register. Why? Because the number of CPU registers are limited, and they may be busy doing some other task. What happens in such an event... the variable works as if its storage class is auto, i.e. memory(RAM). So, it is recommended to use register storage class only for those variable which are accessed multiple times, like in loops, so that time can be saved for each iteration of accessing the variable from the storage.

Related