1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
#include <iostream>
#include <string>
#include <vector>
#include <ctime>
#include <fstream>
#include <iterator>
std::vector<std::string> rev_copy_one_by_one( const std::vector<std::string>& seq, bool reserve, int& num_relocs, int& num_strings_moved )
{
std::vector<std::string> cpy ;
if(reserve) cpy.reserve( seq.size() ) ;
num_relocs = 0 ;
num_strings_moved = 0 ;
for( const auto& str : seq )
{
if( cpy.size() == cpy.capacity() )
{
++num_relocs ;
num_strings_moved += cpy.size() ;
}
cpy.emplace_back( str.rbegin(), str.rend() ) ;
}
return cpy ;
}
int main()
{
// create a test vector of about a million strings
const std::string path = "/usr/include/elf.h" ;
std::ifstream file(path) ;
const std::vector<std::string> seq { std::istream_iterator<std::string>{file}, std::istream_iterator<std::string>{} } ;
std::vector<std::string> test_vec ;
while( test_vec.size() < 1'000'000 ) test_vec.insert( test_vec.end(), seq.begin(), seq.end() ) ;
std::cout << "test vector has " << test_vec.size() << " strings\n" ;
{
const auto start = std::clock() ;
int relocs = 0 ;
int moves = 0 ;
const auto cpy = rev_copy_one_by_one( test_vec, true, relocs, moves ) ;
const auto end = std::clock() ;
std::cout << " with reserve: " << relocs << " relocations, " << moves << " strings were moved, " << (end-start) * 1000.0 / CLOCKS_PER_SEC << " milliseconds\n" ;
}
{
{
const auto start = std::clock() ;
int relocs = 0 ;
int moves = 0 ;
const auto cpy = rev_copy_one_by_one( test_vec, false, relocs, moves ) ;
const auto end = std::clock() ;
std::cout << "without reserve: " << relocs << " relocations, " << moves << " strings were moved, " << (end-start) * 1000.0 / CLOCKS_PER_SEC << " milliseconds\n" ;
}
}
}
|