#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.
Sysop: | Keyop |
---|---|
Location: | Huddersfield, West Yorkshire, UK |
Users: | 493 |
Nodes: | 16 (2 / 14) |
Uptime: | 03:30:22 |
Calls: | 9,707 |
Calls today: | 2 |
Files: | 13,740 |
Messages: | 6,180,826 |