On 24.07.2024 12:12, Bonita Montero wrote:
#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.
What about template lambda without mentioning std::function()? I have
heard rumors that std::function contains a lot of overhead.
I tried to add such a template lambda version, seems faster:
function<int ( int, int )>: 1.4104
virtual function: 1.1389
template lambda: 0.2689
--- SoupGate-Win32 v1.05
* Origin: fsxNet Usenet Gateway (21:1/5)