- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
看完Why is it faster to process a sorted array than an unsorted array? ,我在主循环中添加了一个额外的测试。似乎这个额外的测试使程序更快。
int main()
{
// Generate data
const unsigned arraySize = 32768;
int data[arraySize];
for (unsigned c = 0; c < arraySize; ++c)
data[c] = std::rand() % 256;
//Don't sort the array
//std::sort(data, data + arraySize);
// Test
clock_t start = clock();
long long sum = 0;
for (unsigned i = 0; i < 100000; ++i)
{
// Primary loop
for (unsigned c = 0; c < arraySize; ++c)
{
if (data[c] >= 128)
sum += data[c];
//With this additional test, execution becomes faster
if (data[c] < 128)
sum += data[c];
}
}
double elapsedTime = static_cast<double>(clock() - start) / CLOCKS_PER_SEC;
std::cout << elapsedTime << std::endl;
std::cout << "sum = " << sum << std::endl;
}
通过附加测试我得到了大约 4.2 秒,在没有附加测试的情况下我得到了 18 秒。额外的测试不应该让程序变慢而不是变快吗?
最佳答案
因为那个特别的额外的测试,这个的等效代码:
for (unsigned i = 0; i < 100000; ++i)
{
// Primary loop
for (unsigned c = 0; c < arraySize; ++c)
{
if (data[c] >= 128)
sum += data[c];
//With this additional test, execution becomes faster
if (data[c] < 128)
sum += data[c];
}
}
变成这样:
for (unsigned i = 0; i < 100000; ++i)
{
// Primary loop
for (unsigned c = 0; c < arraySize; ++c)
{
sum += data[c];//because exactly one condition is guaranteed to be
//true in each iteration (in your code)!
//the equivalent is as if there is no condition at all!
}
}
这就是它变得更快的原因。
这是因为不寻常额外的测试和相同主体,编译器能够优化代码,删除if
条件.当你有一个 if
时,编译器就不能这样做。
尝试这样写:
sum -= data[c]; //the body is not identical anymore!
在 if
条件之一中。我确信编译器不会能够优化代码。它现在应该发出较慢的机器代码。
请注意,外部循环可以完全省略,尽管它不太依赖于额外的测试::
// Primary loop
for (unsigned c = 0; c < arraySize; ++c)
{
sum += 100000 * data[c];
}
或者,这个:
// Primary loop
for (unsigned c = 0; c < arraySize; ++c)
{
sum += data[c];
}
sum = 100000 * sum; //multiple once!
关于c++ - 附加条件语句使程序更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13663443/
我有一个与此类似的循环。 int total1, total2; for (total1 = fsize(myfile);;) { total2 = fsize(myfile); ..
我已经开始了一个小项目来尝试学习一些新概念(希望是 C++ 或 Python),我只是希望在我的想法开始时得到一点帮助。 *这一切都与一个更大的梦幻篮球项目有关,但我必须从某个地方开始。 我想要 10
我有以下实体: @Entity public class User { @ManyToOne @JoinColumn(name = "group_code", referencedCo
我正在尝试使用 hibernate 条件向 Join 子句添加附加条件。事实上,有一些方法可以做到这一点: createCriteria(String associationPath, String
我是一名优秀的程序员,十分优秀!