这是一段看似非常特殊的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) 有时,我希望能够测量两段代码之间的经过时间.这仅仅是为了能够检测代码中的瓶颈并改进可以改进的内容.
我想设计一个类似于函数的函数,其中函数应该使用全局变量,该变量回显当前调用和上次调用之间经过的时间.
这样,您可以一个接一个地使用它.
并且该函数应该能够计算分数秒的差异,例如0.1秒或0.3秒等.
一个例子可能会更好地解释它.
echo time_elapsed();
// This echo outputs nothing cause this is the starting case.
// There is nothing to compare against.
//
// 1st code section here
//
echo time_elapsed();
// This echo outputs 0.5 seconds.
// ...which means there has been 0.5 seconds passed
// ...since the last time time_elapsed() was fired
//
// 2nd code section here
//
echo time_elapsed()
// This echo outputs 0.2 seconds
//
// 3rd code section here
//
echo …Run Code Online (Sandbox Code Playgroud)