这是一段看似非常特殊的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( array[i]==false )
array[i]=true;
Run Code Online (Sandbox Code Playgroud)
我想知道它是否应该重写为
array[i]=true;
Run Code Online (Sandbox Code Playgroud)
这就提出了一个问题:比例分配的速度快吗?
从语言到语言的差异怎么样?(例如java和cpp之间的对比)
注意:我听说"过早优化是所有邪恶的根源." 我不认为这适用于:)