I had the idea that an unordered_map with copying the contents to aunsorted.reserve( 1'000'000 );
vector and sorting afterwards might be faster than constructing a
similar map<>, which is sorted by nature. So I wrote some code for
that:
#include <iostream>
#include <chrono>
#include <unordered_map>
#include <map>
#include <algorithm>
#include <vector>
using namespace std;
using namespace chrono;
int main()
{
˙˙˙˙auto tm = []( char const *head, auto fn )
˙˙˙˙{
˙˙˙˙˙˙˙ auto start = high_resolution_clock::now();
˙˙˙˙˙˙˙ fn();
˙˙˙˙˙˙˙ cout << head << duration_cast<nanoseconds>( high_resolution_clock::now() - start ).count() / 1.0e9 << endl;
˙˙˙˙};
˙˙˙˙tm( "unordered->sort: ",
˙˙˙˙˙˙˙ [&]()
˙˙˙˙˙˙˙ {
˙˙˙˙˙˙˙˙˙˙˙ unordered_map<unsigned, unsigned> unsorted;
˙˙˙˙˙˙˙˙˙˙˙ for( unsigned i = 0; i != 1'000'000; ++i )
˙˙˙˙˙˙˙˙˙˙˙˙˙˙˙ unsorted.emplace( i, i );
˙˙˙˙˙˙˙˙˙˙˙ vector<pair<unsigned, unsigned>> sorted;
˙˙˙˙˙˙˙˙˙˙˙ sorted.reserve( unsorted.size() );
˙˙˙˙˙˙˙˙˙˙˙ copy( unsorted.begin(), unsorted.end(), back_inserter(
sorted ) );
˙˙˙˙˙˙˙˙˙˙˙ sort( sorted.begin(), sorted.end(), []( auto &lhs, auto
&rhs ) { return lhs.first < rhs.first; } );
˙˙˙˙˙˙˙ } );
˙˙˙˙tm( "ordered: ",
˙˙˙˙˙˙˙ [&]()
˙˙˙˙˙˙˙ {
˙˙˙˙˙˙˙˙˙˙˙ map<unsigned, unsigned> sorted;
˙˙˙˙˙˙˙˙˙˙˙ for( unsigned i = 0; i != 1'000'000; ++i )
˙˙˙˙˙˙˙˙˙˙˙˙˙˙˙ sorted.emplace( i, i );
˙˙˙˙˙˙˙ } );
}
With g++ 12 having a unordered_map and sorting afterwards is about twice
as fast:
˙˙˙˙unordered->sort: 0.0476365
˙˙˙˙ordered: 0.0908241
With MSVC both versions are much slower:
˙˙˙˙unordered->sort: 0.204837
˙˙˙˙ordered: 0.0862239
I think with MSVC the memory allocator must be much more conservative
than libstdc++'s thread-caching allocator.
I had the idea that an unordered_map with copying the contents to a
vector and sorting afterwards might be faster than constructing a
similar map<>, which is sorted by nature. So I wrote some code for
On 03/01/24 7:03 AM, Bonita Montero wrote:
I had the idea that an unordered_map with copying the contents to a
vector and sorting afterwards might be faster than constructing a
similar map<>, which is sorted by nature. So I wrote some code for
Um... This is common knowledge. ...
The on-line nature of `std::map`-based sorting is the luxury for which
you pay in extra overhead.
Sysop: | Tetrazocine |
---|---|
Location: | Melbourne, VIC, Australia |
Users: | 6 |
Nodes: | 8 (0 / 8) |
Uptime: | 27:46:02 |
Calls: | 45 |
Files: | 21,492 |
Messages: | 63,148 |