Bonita Montero
2024-07-24 09:12:43 UTC
#include <iostream>
#include <functional>
#include <chrono>
#include <atomic>
using namespace std;
using namespace chrono;
function<int ( int, int )> fn( []( int a, int b ) { return a + b; } );
struct V
{
virtual int operator ()( int a, int b )
{
return a + b;
}
};
unique_ptr<V> v( make_unique<V>() );
int main()
{
int sum = 0;
auto bench = [&]<typename Fn>( char const *what, Fn fn )
{
using hr_t = high_resolution_clock;
using dur_t = hr_t::duration;
dur_t tMin = dur_t::max();
for( int turn = 100; turn--; )
{
auto start = hr_t::now();
for( int a = 1'000; a--; )
for( int b = 1'000; b--; )
sum += fn( a, b );
dur_t dur = hr_t::now() - start;
tMin = tMin > dur ? dur : tMin;
}
cout << what << duration_cast<nanoseconds>( tMin ).count() / 1.0e6 <<
endl;
};
bench( "function<int ( int, int )>: ", []( int a, int b ) { return
::fn( a, b ); } );
bench( "virtual function: ", []( int a, int b ) { return (*::v)( a, b
); } );
return sum;
}
I thought that the virtual call is somewhat faster because the functon
checks for an empty function<>-object and throws appropriately, but on
my Zen4-system the virtual operator () and the function<> are about 1.1
nanoseconds per call.
#include <functional>
#include <chrono>
#include <atomic>
using namespace std;
using namespace chrono;
function<int ( int, int )> fn( []( int a, int b ) { return a + b; } );
struct V
{
virtual int operator ()( int a, int b )
{
return a + b;
}
};
unique_ptr<V> v( make_unique<V>() );
int main()
{
int sum = 0;
auto bench = [&]<typename Fn>( char const *what, Fn fn )
{
using hr_t = high_resolution_clock;
using dur_t = hr_t::duration;
dur_t tMin = dur_t::max();
for( int turn = 100; turn--; )
{
auto start = hr_t::now();
for( int a = 1'000; a--; )
for( int b = 1'000; b--; )
sum += fn( a, b );
dur_t dur = hr_t::now() - start;
tMin = tMin > dur ? dur : tMin;
}
cout << what << duration_cast<nanoseconds>( tMin ).count() / 1.0e6 <<
endl;
};
bench( "function<int ( int, int )>: ", []( int a, int b ) { return
::fn( a, b ); } );
bench( "virtual function: ", []( int a, int b ) { return (*::v)( a, b
); } );
return sum;
}
I thought that the virtual call is somewhat faster because the functon
checks for an empty function<>-object and throws appropriately, but on
my Zen4-system the virtual operator () and the function<> are about 1.1
nanoseconds per call.