我想了解一下程序在将变量的值复制到另一个变量之前进行比较会有多大性能提升(这个将在例子中更好地解释),但我发现了一些奇怪的问题。我有以下两段代码:
string a = "";
for (int i = 0; i < 1000000; i++) a += 'a';
for (int i = 0; i < 1000000; i++) {
if ('b' == a.at(i));//compare the two chars directly
}
并且
string a = "";
for (int i = 0; i < 100000000; i++) a += 'a';
for (int i = 0; i < 100000000; i++) {
char c = a.at(i);//declare a new variable
if ('b' == c);//compare the char with the newly created variable,
//instead of comparing it to the other char directly
}
我原以为第二段会比第一段执行时间长,因为多声明了一个变量。但实际测试后发现,第二段所需的时间比第一段还要更短。我进行了几次测试,结果表明第二段总是需要少约0.13秒的时间才能完成执行。以下是完整代码:
#include <string>
#include <iostream>
#include <ctime>
using namespace std;
int main() {
clock_t timer;
string a = "";
string b;
for (int i = 0; i < 100000000; i++)
a += "a";
timer = clock();
for (int i = 0; i < 100000000; i++) {
if ('b'==a.at(i)) b += "a";
}
cout << (clock()-timer)/(float)CLOCKS_PER_SEC << "sec" << endl;
timer = clock();
for (int i = 0; i < 100000000; i++) {
char c = a.at(i);
if ('b'==c) b += "a";
}
cout << (clock()-timer)/(float)CLOCKS_PER_SEC << "sec" << endl;
return 0;
}
为什么会发生这种情况?
编辑:我遵循NathanOliver的建议,为每个循环添加了单独的字符串,所以现在代码看起来像这样:
#include <string>
#include <iostream>
#include <ctime>
using namespace std;
int main() {
clock_t timer;
string compare_string_1 = "";
string compare_string_2 = "";
string segment_1 = "";
string segment_2 = "";
for (int i = 0; i < 100000000; i++)
compare_string_1 += "a";
for (int i = 0; i < 100000000; i++)
compare_string_2 += "a";
timer = clock();
for (int i = 0; i < 100000000; i++) {
if ('b'==compare_string_1.at(i)) segment_1 += "a";
}
cout << (clock()-timer)/(float)CLOCKS_PER_SEC << "sec" << endl;
timer = clock();
for (int i = 0; i < 100000000; i++) {
char c = compare_string_2.at(i);
if ('b'==c) segment_2 += "a";
}
cout << (clock()-timer)/(float)CLOCKS_PER_SEC << "sec" << endl;
return 0;
}
char
变量实际上不需要任何时间。对于这两个循环,生成的代码很可能是相同的(将a.at(i)
放入寄存器中,将寄存器与'b'
进行比较)。(虽然这不是您实际的代码 -b
从未声明。复制和粘贴似乎已经失传了。) - molbdnilo