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 58
|
#include <algorithm>
#include <cctype>
#include <chrono>
#include <iostream>
#include <string>
using sys_clock = std::chrono::system_clock;
int main()
{
const std::string str{
R"("Beware the Jabberwock, my son!
The jaws that bite, the claws that catch!
Beware the Jubjub bird, and shun
The frumious Bandersnatch!")"
};
double t_count_if{};
{
std::cout << "--- count_if() ---\n";
std::size_t count{};
auto start = sys_clock::now( );
count = std::count_if( str.begin( ), str.end( ), ispunct );
auto end = sys_clock::now( );
t_count_if = std::chrono::duration_cast< std::chrono::duration<double, std::micro> >( end - start ).count( );
std::cout << "punctuation count = " << count << "\n";
std::cout << "elapsed: " << t_count_if << " microseconds\n\n";
}
double t_count{};
{
std::cout << "--- count() ---\n";
std::size_t count{};
auto start = sys_clock::now( );
count += std::count( str.begin( ), str.end( ), '.' );
count += std::count( str.begin( ), str.end( ), ',' );
count += std::count( str.begin( ), str.end( ), '!' ); // missed this one
count += std::count( str.begin( ), str.end( ), '?' );
count += std::count( str.begin( ), str.end( ), ':' );
count += std::count( str.begin( ), str.end( ), ';' );
auto end = sys_clock::now( );
t_count = std::chrono::duration_cast< std::chrono::duration<double, std::micro> >( end - start ).count( );
std::cout << "punctuation count = " << count << "\n";
std::cout << "elapsed: " << t_count << " microseconds\n\n";
}
if( t_count_if < t_count )
std::cout << "count_if() is faster by " << t_count - t_count_if << " microseconds\n";
else
std::cout << "count() is faster by " << t_count_if - t_count << " microseconds\n";
}
|