这是一段看似非常特殊的C++代码.出于某种奇怪的原因,奇迹般地对数据进行排序使得代码几乎快了六倍.
#include <algorithm>
#include <ctime>
#include <iostream>
int main()
{
// Generate data
const unsigned arraySize = 32768;
int data[arraySize];
for (unsigned c = 0; c < arraySize; ++c)
data[c] = std::rand() % 256;
// !!! With this, the next loop runs faster.
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) …Run Code Online (Sandbox Code Playgroud) 用if else或&&和||编码是否有区别?运营商.
例如,在if-else样式中,我可以编写此代码
for( var i = 0; i < 1000000000; i ++ ) {
if( i % 2 == 0 ) {
f1();
} else {
f2();
}
}
Run Code Online (Sandbox Code Playgroud)
在&&和||中 样式我可以使用此代码获得相同的结果
(( i % 2 == 0 ) && (test1() || true)) || test2();
Run Code Online (Sandbox Code Playgroud)
我在JS中测试它们,它们大约在同一时间工作,但我没有在C++上测试它们.也许它取决于编译器或语言.
有速度差吗?还是有什么不同?
谢谢
它背后有什么逻辑吗?
>>>'a' and 'b' and 'c'
'c'
>>>'a' or 'b' or 'c'
'a'
Run Code Online (Sandbox Code Playgroud) c++ ×2
if-statement ×1
java ×1
javascript ×1
optimization ×1
performance ×1
python ×1
python-2.7 ×1