我在64位计算机上使用GCC编译器。 当我鬼混时,我发现以下代码具有恒定的执行时间(我使用Unix time命令)为: 代码:
#include<stdio.h>
#include <string.h>
#include<stdlib.h>
#define bufferSize 5010
#define numberOfElements 100
#define sizeOfEachNumber 50
FILE* openFile(){
return fopen("file.txt","r");
}
int closeFile(FILE* file){
return fclose(file);
}
char* getAllData(FILE* file,char* buffer){
fgets(buffer,bufferSize,file);
return buffer;
}
void showData(char *buffer){
printf("The data in the buffer is:%s\n", buffer);
}
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;
}
时间:
real 0m0.003s
user 0m0.003s
sys 0m0.000s
但是我改变了一件小事情,那就是函数seperateDataTo50DigitNumbers:
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");
}
}
}
我希望代码更快,因为变量现在存储在处理器的寄存器中,但是我得到的时间却是变化的(有时甚至比第一个代码还要长): 时间:
real 0m0.003s
user 0m0.003s
sys 0m0.001s
real 0m0.003s
user 0m0.000s
sys 0m0.004s
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
寄存器变量对程序的影响如此之大,实在令人惊讶,有人可以告诉我原因。以及何时应该使用寄存器变量来优化代码。
答案 0 :(得分:1)
如果 r.c 是:
#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");
}
}
}
我愿意:
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 $
生成代码完全相同,我并不感到惊讶
执行时间太短(并且没有与寄存器相关的部分执行时间,但肯定是 printf 执行更多代码),并且差异不明显