I read about cache recently, so I tried to benchmark some code. I use two dependencies here - Timer for measuring tests and Random::value for randomizing values in array.
#include "../../Core/Include/Timer.hpp"
#include "../../Core/Include/Math.hpp"
#include <algorithm>
#include <iostream>
constexpr auto TEST_SIZE = 50'000;
int main()
{
std::array<int, TEST_SIZE> arraySorted;
std::array<int, TEST_SIZE> arrayNotSorted;
std::vector<int> vectorSorted( TEST_SIZE );
std::vector<int> vectorNotSorted( TEST_SIZE );
// Filing with random data.
for ( uint16_t i = 0; i < TEST_SIZE; i++ ) {
auto rndVal = Random::value( -1024, 1024 );
vectorNotSorted[i] = vectorSorted[i] = arrayNotSorted[i] = arraySorted[i] = rndVal;
}
// Sorting containers.
std::sort( arraySorted.begin(), arraySorted.end() );
std::sort( vectorSorted.begin(), vectorSorted.end() );
Timer timer;
// Testing.
timer.Reset();
for ( auto& val : arraySorted )
val = Random::value( 0, 1 );
std::cout << "arraySorted: " << timer.GetMicroseconds() << "ms\n";
timer.Reset();
for ( auto& val : arrayNotSorted )
val = Random::value( 0, 1 );
std::cout << "arrayNotSorted: " << timer.GetMicroseconds() << "ms\n";
timer.Reset();
for ( auto& val : vectorSorted )
val = Random::value( 0, 1 );
std::cout << "vectorSorted: " << timer.GetMicroseconds() << "ms\n";
timer.Reset();
for ( auto& val : vectorNotSorted)
val = Random::value( 0, 1 );
std::cout << "vectorNotSorted: " << timer.GetMicroseconds() << "ms\n";
std::cin.get();
}
And my results are strange - output is:
arraySorted: 1889ms
arrayNotSorted: 1879ms
vectorSorted: 1931ms
vectorNotSorted: 1878ms
Shouldn't sorted be faster than not sorted?
Aucun commentaire:
Enregistrer un commentaire