考虑以下代码:
println()
在我的计算机上(Visual Studio 2017,发布模式生成),这四种情况的输出为:
System.out.println( "Point 1 - " + point1.toString() + ";\n"
+ "Point 2 - " + point2.toString() + ";\n"
+ "Point 3 - " + point3.toString() + ";\n"
+ "Point 4 - " + point4.toString() + ";" );
情况(1),我可以理解为什么#include <stdio.h>
#include <stdlib.h>
#include <time.h>
class chartolower {
private:
char s[50000];
public:
void populates(int index, int val) { s[index] = val; }
size_t strlen(const char *s) const {
long length = 0;
while (*s != '\0') {
s++;
length++;
}
return length;
}
/*Convert string to lower case: slow*/
void lower1() {
long i;
for (i = 0; i < strlen(s); i++)
if (s[i] >= 'A' && s[i] <= 'Z')
s[i] -= ('A' - 'a'); //Case(1) strlen(s) not optimized away
//i = i; //Case(2) strlen(s) optimized away
//if(s[i] != '\0') s[i] = s[i];//Case(3) strlen(s) not optimized away
//s[i] = s[i]; //Case(4) strlen(s) not optimized away
}
};
int main() {
chartolower s;
for (int i = 0; i < 49999; i++)
s.populates(i, 65);//ASCII for A
s.populates(49999, '\0');
clock_t start_t, end_t, total_t;
start_t = clock();
s.lower1();
end_t = clock();
total_t = (end_t - start_t);
printf("Total time taken by CPU Lower 1: %d\n", total_t);
getchar();
}
行的Case(1) Total time taken by CPU Lower 1: 3477
Case(2) Total time taken by CPU Lower 1: 0
Case(3) Total time taken by CPU Lower 1: 3445
Case(4) Total time taken by CPU Lower 1: 3455
不能被优化,因为可以更改strlen(s)
。对于情况(2),由于所有for (i = 0; i < strlen(s); i++)
的{{1}}保持不变,因此已对其进行了优化。 Case(3)对我来说尚不清楚为什么编译器无法优化s[i]
。我希望编译器会弄清楚s[i]
应该进行计算,直到遇到i
为止,而这恰恰是Case(3)中检查的条件。 Case(4)也不优化,我想应该将其优化,因为它类似于Case(2)。
是什么导致Case(2)中的优化,而不是其他情况?