On 07.11.2019 17:46, Bonita Montero wrote:
>>> I just found that alloca() with MSVC isn't that fast that it could be.
>
>> Checking things out, at least in a little toy test program the
>> standard allocation with g++ is amazingly fast.
>
> Of course alloca() is very fast if you don't have this stupid stack
> -touching.
No no, the numbers shown were about ordinary `std::alloc` versus a
simple stack like arena allocator, used for `std::basic_string`.
Used like this:
#include <my/arena/all.hpp>
#include <chrono>
#include <type_traits> // std::conditional_t
namespace my {
namespace chrono = std::chrono;
using std::conditional_t;
using Timer_clock =
conditional_t<chrono::high_resolution_clock::is_steady,
chrono::high_resolution_clock, chrono::steady_clock
>;
template< class Rep, class Period >
inline auto as_seconds( const chrono::duration<Rep, Period>
duration_value )
-> double
{ return chrono::duration<double>( duration_value ).count(); }
} // namespace my
auto common_storage()
-> my::arena::Storage&
{
static auto the_storage = my::arena::Storage( 2'000'000 );
return the_storage;
}
void test_arena_allocator()
{
using std::basic_string, std::char_traits, std::cout, std::endl;
namespace arena = my::arena;
using String = basic_string<char, char_traits<char>,
my::arena::Allocator<char>>;
const auto start_time = my::Timer_clock::now();
auto& storage = common_storage();
auto allocator = my::arena::Allocator<char>( storage );
auto s = String( allocator ); // Awkward!
for( int i = 1; i <= 987'654; ++i ) {
s += '-';
}
const auto end_time = my::Timer_clock::now();
cout << "Arena alloc: "
<< s.length() << " chars"
<< " in " << my::as_seconds( end_time - start_time ) << "
seconds."
<< endl;
}
void test_std_allocator()
{
using std::string, std::cout, std::endl;
const auto start_time = my::Timer_clock::now();
auto s = string();
for( int i = 1; i <= 987'654; ++i ) {
s += '-';
}
const auto end_time = my::Timer_clock::now();
cout << "Standard alloc: "
<< s.length() << " chars"
<< " in " << my::as_seconds( end_time - start_time ) << "
seconds."
<< endl;
}
auto main() -> int
{
using std::vector;
{ (void) vector<char>( 1'234'567 ); } // Prime the runtime
library stuff.
for( int i = 1; i <= 5; ++i ) {
test_arena_allocator();
test_std_allocator();
}
}
- Alf