简体   繁体   中英

Register variables cause execution time to vary, why?

While fooling around i found out that the following code has a constant execution time(I used the Unix time command) as: CODE:

    #define bufferSize 5010
    void seperateDataTo50DigitNumbers(char *buffer){
        unsigned int length = strlen(buffer);
        for (int i = 1; i <= length; ++i){
            printf("%c", buffer[i - 1]);
            if(i%50 == 0){
                printf("\n");
            }
        }
    }
    int main(int argc, char const *argv[])
    {
        char buffer[bufferSize];
        FILE *file;
        file = openFile();
        getAllData(file,buffer);
        seperateDataTo50DigitNumbers(buffer);
        closeFile(file);
        return 0;
    }

TIME:

real    0m0.003s
user    0m0.003s
sys     0m0.000s

But I changed one small thing:

    void seperateDataTo50DigitNumbers(char *buffer){
        register unsigned int length = strlen(buffer);
        for (register int i = 1; i <= length; ++i){
            printf("%c", buffer[i - 1]);
            if(i%50 == 0){
                printf("\n");
            }
        }
    }

I expected the code to be faster as the variables are now stored in the register of the processor but instead, the time varies:

real    0m0.003s
user    0m0.003s
sys     0m0.000s


real    0m0.003s
user    0m0.001s
sys     0m0.003s


real    0m0.004s
user    0m0.001s
sys     0m0.003s

real    0m0.003s
user    0m0.000s
sys     0m0.003s

Could anyone tell me the reason for this? And when should we use the register variables to optimise the code?

if rc is :

#include <stdio.h>
#include <string.h>

void seperateDataTo50DigitNumbersR(char *buffer){
    REGISTER unsigned int length = strlen(buffer);
    for (REGISTER int i = 1; i <= length; ++i){
        printf("%c", buffer[i - 1]);
        if(i%50 == 0){
            printf("\n");
        }
    }
}

I do :

pi@raspberrypi:/tmp $ gcc -S -O3 -DREGISTER= r.c -o r.s1
pi@raspberrypi:/tmp $ gcc -S -O3 -DREGISTER=register r.c -o r.s2
pi@raspberrypi:/tmp $ diff r.s1 r.s2
pi@raspberrypi:/tmp $ 

the generate code are exactely the same, and I am not surprised

  • first the compilers are very good and do not need uour help to produce a good code
  • second you call a function ( printf ) so it is not possible to have the values all the time in registers except on CPU saving page of registers ... and in that case the compiler does that by itself

Out of that the execution times are too small (and not done in part associated to the registers but surely the printf executing more code) and the differences are not significant

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM