mirror of
https://github.com/Light-City/CPlusPlusThings.git
synced 2026-10-28 19:04:45 +08:00
- const README: rewrite the space-saving claim per issue #5 follow-ups (constant-expression const vs #define immediates; which const qualify as constant expressions) - const README: fix the class-section diagnosis per issue #338 (overload resolution picks the const overload; the restriction only surfaces once that overload is removed) - sizeof README: virtual-inheritance result is compiler-dependent (GCC merges vbptr+vfptr -> 16, MSVC keeps them separate -> 32) #246 - static README: new section on internal linkage / access restriction with anonymous-namespace comparison #142 - 10-day practice: full problem list table + fixed day links #136 - new design_pattern/singleton/singleton_default.hpp: reusable thread-safe CRTP singleton template, compile+concurrency tested #303
1.3 KiB
1.3 KiB
来自 C++那些事网站 的文章,由站点同步脚本导出。
C++ std::bind 与 lambda 对比
https://quick-bench.com/q/CEnR_XUuIwnZxaP4KJNSlpYG38c
#include <functional>
#include <numeric>
#include <vector>
struct Calculator {
int count{1};
int total{0};
auto calculate() -> void {
using std::iota, std::vector;
// Random math
vector<int> u(8), v(Calculator::count * u.size());
iota(v.begin(), v.end(), *u.begin());
int sum{*v.begin() + *u.begin()};
for (size_t pos{0}; pos < v.size(); ++pos) {
sum += u[pos % u.size()] * v[pos];
}
Calculator::total += sum;
++Calculator::count;
}
};
// auto f(std::function<void(int)> g) -> void { g(rand()); }
template<typename FN> auto f(FN g) -> void { g(rand()); }
static auto BM_bind(benchmark::State& state) -> void {
Calculator calculator;
for (auto _ : state) {
f(std::bind(&Calculator::calculate, &calculator));
}
}
static auto BM_lambda(benchmark::State& state) -> void {
Calculator calculator;
for (auto _ : state) {
f([&calculator]([[maybe_unused]] int x) { calculator.calculate(); });
}
}
BENCHMARK(BM_bind);
BENCHMARK(BM_lambda);