a[mask] = f(a[mask]) on NEON. faster than the obvious blend
## Problem
Apply an operation to elements that satisfy a condition:
for (size_t i = 0; i < n; ++i)
if (mask(a[i])) a[i] = f(a[i]);
### Notes
- `a[i] ∈ (0, 1)`, `thd ∈ (0, 1)`, `mask = a[i] < thd`; uniform distribution (except at the end of the article)
- `f` is one of `sqrt`, `frfrexp` (mantissa), `sin` 3.5 ULP, `sin` 1 ULP, `pow` 1 ULP (from SLEEF)
- `f` and `mask` are passed as runtime values, so they are wrapped in a lambda with `always_inline`, otherwise they may
not be inlined
- The array size `n` is a multiple of every unroll, tile etc. The tail is trivial to handle(BSL/scalar)
- In tables `*` = best, units = GiB/s
- Don't compare numbers across tables. Different conditions, values fluctuate
- All benchmarks: Apple M5; clang++ -O3 -std=c++23 -march=native; GiB/s = (n * 4 bytes) / time, min of 720 runs
(During bench, functions run in a changing order, data is restored ofc); n=1e7 + 2432;
## BSL blend
If the problem is memory bound (cheap function or high density), the standard algorithm is optimal:
template <bool Skip>
void bsl(float* dst, const size_t n, auto f, auto mask) {
for (size_t i = 0; i < n; i += 16) {
std::array<float32x4_t, 4> v;
for (size_t j = 0; j < 4; ++j) v[j] = vld1q_f32(dst + i + 4 * j);
std::array<uint32x4_t, 4> m;
for (size_t j = 0; j < 4; ++j) m[j] = mask(v[j]);
if constexpr (Skip) {
if (vmaxvq_u32(vaddq_u32(vaddq_u32(m[0], m[1]), vaddq_u32(m[2], m[3]))) == 0) continue;
}
for (size_t j = 0; j < 4; ++j) vst1q_f32(dst + i + 4 * j, vbslq_f32(m[j], f(v[j]), v[j]));
}
}
It computes `f` on every element, but stores only the selected ones.
Skip helps on sparse masks, but otherwise mispredictions will kill performance. We'll need it later.
But for expensive `f` this algo does too much extra work
## Detour
To avoid unnecessary work, we compress selected elements, apply only to them, and expand back.
avx512 does this in two instructions. NEON doesn't, so we'll emulate and optimize.
constexpr size_t tile = 4096;
constexpr std::array<uint32_t, 4> weights{1 + 16, 2 + 16, 4 + 16, 8 + 16};
constexpr auto cps_tbl = compress_table();
constexpr auto exp_tbl = expand_table();
std::array<float, tile + 16> tmp;
std::array<uint8_t, tile / 4 + 3> s;
std::array<uint16_t, tile / 4 + 3> idx; // idx, D and B come in later
constexpr double D = 0.845;
constexpr double B = 0.3;
template <bool Skip>
size_t detour(float* dst, const size_t n, const auto w, auto f, auto mask) {
float* ptr = tmp.data();
for (size_t i = 0; i < n; i += 16) {
std::array<float32x4_t, 4> v;
for (size_t j = 0; j < 4; ++j) v[j] = vld1q_f32(dst + i + 4 * j);
std::array<uint32x4_t, 4> m;
for (size_t j = 0; j < 4; ++j) m[j] = mask(v[j]);
if constexpr (Skip)
if (vmaxvq_u32(vaddq_u32(vaddq_u32(m[0], m[1]), vaddq_u32(m[2], m[3]))) == 0) {
s[i / 4] = s[i / 4 + 1] = s[i / 4 + 2] = s[i / 4 + 3] = 0;
continue;
}
std::array<uint32_t, 4> sk;
for (size_t j = 0; j < 4; ++j) {
sk[j] = vaddvq_u32(vandq_u32(m[j], w));
s[i / 4 + j] = sk[j];
}
std::array<size_t, 4> off; off[0] = 0;
for (size_t j = 1; j < 4; ++j) off[j] = off[j - 1] + (sk[j - 1] >> 4);
std::array<uint8x16_t, 4> index;
for (size_t j = 0; j < 4; ++j) index[j] = vld1q_u8(cps_tbl[sk[j] & 15].data());
for (size_t j = 0; j < 4; ++j) vst1q_f32(ptr + off[j], vreinterpretq_f32_u8(vqtbl1q_u8(vreinterpretq_u8_f32(v[j]), index[j])));
ptr += off[3] + (sk[3] >> 4);
}
const size_t size = ptr - tmp.data();
if (size == 0) return size;
ptr = tmp.data();
for (size_t i = 0; i < size; i += 16) {
## Problem
Apply an operation to elements that satisfy a condition:
for (size_t i = 0; i < n; ++i)
if (mask(a[i])) a[i] = f(a[i]);
### Notes
- `a[i] ∈ (0, 1)`, `thd ∈ (0, 1)`, `mask = a[i] < thd`; uniform distribution (except at the end of the article)
- `f` is one of `sqrt`, `frfrexp` (mantissa), `sin` 3.5 ULP, `sin` 1 ULP, `pow` 1 ULP (from SLEEF)
- `f` and `mask` are passed as runtime values, so they are wrapped in a lambda with `always_inline`, otherwise they may
not be inlined
- The array size `n` is a multiple of every unroll, tile etc. The tail is trivial to handle(BSL/scalar)
- In tables `*` = best, units = GiB/s
- Don't compare numbers across tables. Different conditions, values fluctuate
- All benchmarks: Apple M5; clang++ -O3 -std=c++23 -march=native; GiB/s = (n * 4 bytes) / time, min of 720 runs
(During bench, functions run in a changing order, data is restored ofc); n=1e7 + 2432;
## BSL blend
If the problem is memory bound (cheap function or high density), the standard algorithm is optimal:
template <bool Skip>
void bsl(float* dst, const size_t n, auto f, auto mask) {
for (size_t i = 0; i < n; i += 16) {
std::array<float32x4_t, 4> v;
for (size_t j = 0; j < 4; ++j) v[j] = vld1q_f32(dst + i + 4 * j);
std::array<uint32x4_t, 4> m;
for (size_t j = 0; j < 4; ++j) m[j] = mask(v[j]);
if constexpr (Skip) {
if (vmaxvq_u32(vaddq_u32(vaddq_u32(m[0], m[1]), vaddq_u32(m[2], m[3]))) == 0) continue;
}
for (size_t j = 0; j < 4; ++j) vst1q_f32(dst + i + 4 * j, vbslq_f32(m[j], f(v[j]), v[j]));
}
}
It computes `f` on every element, but stores only the selected ones.
Skip helps on sparse masks, but otherwise mispredictions will kill performance. We'll need it later.
But for expensive `f` this algo does too much extra work
## Detour
To avoid unnecessary work, we compress selected elements, apply only to them, and expand back.
avx512 does this in two instructions. NEON doesn't, so we'll emulate and optimize.
constexpr size_t tile = 4096;
constexpr std::array<uint32_t, 4> weights{1 + 16, 2 + 16, 4 + 16, 8 + 16};
constexpr auto cps_tbl = compress_table();
constexpr auto exp_tbl = expand_table();
std::array<float, tile + 16> tmp;
std::array<uint8_t, tile / 4 + 3> s;
std::array<uint16_t, tile / 4 + 3> idx; // idx, D and B come in later
constexpr double D = 0.845;
constexpr double B = 0.3;
template <bool Skip>
size_t detour(float* dst, const size_t n, const auto w, auto f, auto mask) {
float* ptr = tmp.data();
for (size_t i = 0; i < n; i += 16) {
std::array<float32x4_t, 4> v;
for (size_t j = 0; j < 4; ++j) v[j] = vld1q_f32(dst + i + 4 * j);
std::array<uint32x4_t, 4> m;
for (size_t j = 0; j < 4; ++j) m[j] = mask(v[j]);
if constexpr (Skip)
if (vmaxvq_u32(vaddq_u32(vaddq_u32(m[0], m[1]), vaddq_u32(m[2], m[3]))) == 0) {
s[i / 4] = s[i / 4 + 1] = s[i / 4 + 2] = s[i / 4 + 3] = 0;
continue;
}
std::array<uint32_t, 4> sk;
for (size_t j = 0; j < 4; ++j) {
sk[j] = vaddvq_u32(vandq_u32(m[j], w));
s[i / 4 + j] = sk[j];
}
std::array<size_t, 4> off; off[0] = 0;
for (size_t j = 1; j < 4; ++j) off[j] = off[j - 1] + (sk[j - 1] >> 4);
std::array<uint8x16_t, 4> index;
for (size_t j = 0; j < 4; ++j) index[j] = vld1q_u8(cps_tbl[sk[j] & 15].data());
for (size_t j = 0; j < 4; ++j) vst1q_f32(ptr + off[j], vreinterpretq_f32_u8(vqtbl1q_u8(vreinterpretq_u8_f32(v[j]), index[j])));
ptr += off[3] + (sk[3] >> 4);
}
const size_t size = ptr - tmp.data();
if (size == 0) return size;
ptr = tmp.data();
for (size_t i = 0; i < size; i += 16) {
detour<false>(dst + done, tile - done, w, f, mask);
prev = rem * probe / (tile - done);
}
} else {
prev = detour<false>(dst, tile, w, f, mask) * probe / tile;
}
}
} else if (cnt < xlo) {
prev = detour_compact<true>(dst, tile, w, f, mask) * probe / tile;
} else if (cnt < lo) {
prev = detour_compact<false>(dst, tile, w, f, mask) * probe / tile;
} else {
prev = detour<false>(dst, tile, w, f, mask) * probe / tile;
}
dst += tile;
}
}
And v4 easily passes that test. pow10:
| thd | 0 | 1 |
|--------------|--------:|-------:|
| tiled detour | 38.18 | 6.94 |
| pilot v3 | 68.11 | 1.04 |
| pilot v3.5 | 68.67 | 3.84 |
| pilot v4 | 69.51\* | 7.05\* |
| BSL | 1.04 | 1.04 |
btw here thd no longer matches the density. For thd = 0, density = 0, and for thd = 1, density = 9.5%
It beats v3.5 by over 80%. It's also faster than plain tiled detour, because v4 picks detour_compact. This is the final
version.
## Results
v4 vs BSL:
| thd | 0 | 0.05 | 0.1 | 0.2 | 0.3 | 0.4 | 0.5 | 0.6 | 0.7 | 0.8 | 0.9 | 1 |
|:-----------------|--------:|--------:|--------:|--------:|--------:|--------:|--------:|--------:|--------:|--------:|--------:|--------:|
| pilot_v4 sqrt | 69.81\* | 31.99\* | 31.84 | 31.73 | 31.83 | 32.07\* | 31.98 | 31.96\* | 31.96 | 31.89\* | 31.91 | 31.77 |
| BSL sqrt | 31.88 | 31.93 | 31.95\* | 31.80\* | 31.89\* | 31.99 | 32.06\* | 31.92 | 31.98\* | 31.75 | 31.93\* | 31.91\* |
| pilot_v4 frfrexp | 69.41\* | 17.21\* | 16.57 | 15.79 | 15.99 | 16.06 | 15.93 | 15.99 | 16.39 | 15.84 | 15.87 | 15.80 |
| BSL frfrexp | 16.79 | 16.87 | 16.82\* | 16.71\* | 16.78\* | 16.88\* | 16.89\* | 16.83\* | 16.89\* | 16.79\* | 16.75\* | 16.75\* |
| pilot_v4 sin10 | 68.19\* | 18.82\* | 14.84\* | 10.84\* | 8.93\* | 7.55\* | 6.56\* | 5.81\* | 5.19\* | 4.69 | 4.68 | 4.68 |
| BSL sin10 | 4.78 | 4.75 | 4.78 | 4.72 | 4.75 | 4.74 | 4.75 | 4.77 | 4.75 | 4.76\* | 4.77\* | 4.77\* |
| pilot_v4 pow10 | 64.17\* | 10.76\* | 6.85\* | 4.04\* | 2.89\* | 2.25\* | 1.85\* | 1.57\* | 1.36\* | 1.20\* | 1.08\* | 1.00 |
| BSL pow10 | 1.02 | 1.02 | 1.02 | 1.01 | 1.01 | 1.01 | 1.02 | 1.02 | 1.02 | 1.02 | 1.02 | 1.01\* |
Against BSL, it loses at worst 6%, but wins big much more often.
To reduce the loss, dispatch can be sped up: use every 4th register in density and bsl_verified. But that helps only if
the density is uniform.
The worst v4 miss I found: 512 dense, 512 empty, then everything is dense until the end of the cycle (17 * 4096).
const size_t cycle = 17 * 4096;
for (size_t i = 0; i < n; ++i) {
dst[i] = i % cycle >= 512 && i % cycle < 1024;
}
This hurts most with the cheapest `f` (with `d_max > 0`, of course):
const auto a = vdupq_n_f32(0.5f);
#pragma unroll
for (int i = 0; i < 13; ++i) x = vfmaq_f32(a, x, a);
return x;
| thd | 0 | 1 |
|--------------|--------:|--------:|
| tiled detour | 38.29 | 9.44 |
| pilot v3 | 74.72 | 15.81\* |
| pilot v3.5 | 74.84 | 15.04 |
| pilot v4 | 74.89\* | 9.84 |
| BSL | 15.61 | 15.60 |
v3.5's biggest loss is limited by BSL, while v4 is limited by detour. And a wrong detour is the cheaper mistake.
So v4 isn't always better, but its misses are less severe.
This problem has no perfect solution. Any dispatch algo can be countertested.
Full code: [godbolt](https://godbolt.org/z/nKhPjEn6v).
https://redd.it/1v94b7w
@r_cpp
prev = rem * probe / (tile - done);
}
} else {
prev = detour<false>(dst, tile, w, f, mask) * probe / tile;
}
}
} else if (cnt < xlo) {
prev = detour_compact<true>(dst, tile, w, f, mask) * probe / tile;
} else if (cnt < lo) {
prev = detour_compact<false>(dst, tile, w, f, mask) * probe / tile;
} else {
prev = detour<false>(dst, tile, w, f, mask) * probe / tile;
}
dst += tile;
}
}
And v4 easily passes that test. pow10:
| thd | 0 | 1 |
|--------------|--------:|-------:|
| tiled detour | 38.18 | 6.94 |
| pilot v3 | 68.11 | 1.04 |
| pilot v3.5 | 68.67 | 3.84 |
| pilot v4 | 69.51\* | 7.05\* |
| BSL | 1.04 | 1.04 |
btw here thd no longer matches the density. For thd = 0, density = 0, and for thd = 1, density = 9.5%
It beats v3.5 by over 80%. It's also faster than plain tiled detour, because v4 picks detour_compact. This is the final
version.
## Results
v4 vs BSL:
| thd | 0 | 0.05 | 0.1 | 0.2 | 0.3 | 0.4 | 0.5 | 0.6 | 0.7 | 0.8 | 0.9 | 1 |
|:-----------------|--------:|--------:|--------:|--------:|--------:|--------:|--------:|--------:|--------:|--------:|--------:|--------:|
| pilot_v4 sqrt | 69.81\* | 31.99\* | 31.84 | 31.73 | 31.83 | 32.07\* | 31.98 | 31.96\* | 31.96 | 31.89\* | 31.91 | 31.77 |
| BSL sqrt | 31.88 | 31.93 | 31.95\* | 31.80\* | 31.89\* | 31.99 | 32.06\* | 31.92 | 31.98\* | 31.75 | 31.93\* | 31.91\* |
| pilot_v4 frfrexp | 69.41\* | 17.21\* | 16.57 | 15.79 | 15.99 | 16.06 | 15.93 | 15.99 | 16.39 | 15.84 | 15.87 | 15.80 |
| BSL frfrexp | 16.79 | 16.87 | 16.82\* | 16.71\* | 16.78\* | 16.88\* | 16.89\* | 16.83\* | 16.89\* | 16.79\* | 16.75\* | 16.75\* |
| pilot_v4 sin10 | 68.19\* | 18.82\* | 14.84\* | 10.84\* | 8.93\* | 7.55\* | 6.56\* | 5.81\* | 5.19\* | 4.69 | 4.68 | 4.68 |
| BSL sin10 | 4.78 | 4.75 | 4.78 | 4.72 | 4.75 | 4.74 | 4.75 | 4.77 | 4.75 | 4.76\* | 4.77\* | 4.77\* |
| pilot_v4 pow10 | 64.17\* | 10.76\* | 6.85\* | 4.04\* | 2.89\* | 2.25\* | 1.85\* | 1.57\* | 1.36\* | 1.20\* | 1.08\* | 1.00 |
| BSL pow10 | 1.02 | 1.02 | 1.02 | 1.01 | 1.01 | 1.01 | 1.02 | 1.02 | 1.02 | 1.02 | 1.02 | 1.01\* |
Against BSL, it loses at worst 6%, but wins big much more often.
To reduce the loss, dispatch can be sped up: use every 4th register in density and bsl_verified. But that helps only if
the density is uniform.
The worst v4 miss I found: 512 dense, 512 empty, then everything is dense until the end of the cycle (17 * 4096).
const size_t cycle = 17 * 4096;
for (size_t i = 0; i < n; ++i) {
dst[i] = i % cycle >= 512 && i % cycle < 1024;
}
This hurts most with the cheapest `f` (with `d_max > 0`, of course):
const auto a = vdupq_n_f32(0.5f);
#pragma unroll
for (int i = 0; i < 13; ++i) x = vfmaq_f32(a, x, a);
return x;
| thd | 0 | 1 |
|--------------|--------:|--------:|
| tiled detour | 38.29 | 9.44 |
| pilot v3 | 74.72 | 15.81\* |
| pilot v3.5 | 74.84 | 15.04 |
| pilot v4 | 74.89\* | 9.84 |
| BSL | 15.61 | 15.60 |
v3.5's biggest loss is limited by BSL, while v4 is limited by detour. And a wrong detour is the cheaper mistake.
So v4 isn't always better, but its misses are less severe.
This problem has no perfect solution. Any dispatch algo can be countertested.
Full code: [godbolt](https://godbolt.org/z/nKhPjEn6v).
https://redd.it/1v94b7w
@r_cpp
godbolt.org
Compiler Explorer - C++ (armv8-a clang (trunk))
consteval auto compress_table() {
std::array<std::array<uint8_t, 16>, 16> index;
std::array<uint8_t, 16> row;
row.fill(255);
index.fill(row);
for (size_t idx = 0; idx < 16; ++idx) {
size_t j = 0;
for (size_t i = 0; i <…
std::array<std::array<uint8_t, 16>, 16> index;
std::array<uint8_t, 16> row;
row.fill(255);
index.fill(row);
for (size_t idx = 0; idx < 16; ++idx) {
size_t j = 0;
for (size_t i = 0; i <…
bindings = korka::make_bindings(
"func", func,
"foo", foo
);
```
But why couldn't I make it work?
In C++ you can't pass a string into `template <auto ...args>`. We need `const_string`. We can't mix types in the one stream of variadic args and make compiler guess it right. Templates require explicitness and it's impossible to write a universal parser.
Variant #2 works, but you can't extract the function into the runtime. You just can't. Functions may have different signatures, but you need to make them all the same type, and create a FFI wrapper along the way. Compile-time doesn't allow `reinterpretet_cast<void*>(&func)`.
So I designed this:
```cpp
constexpr auto bindings = korka::make_bindings(
korka::wrap<fib>("cpp_fib"),
korka::wrap<print_n>("print_n")
);
```
Not so elegant, but still not bad.
`wrap` is very simple
```cpp
// our FFI signature
using vm_external_function_type = void(vm::context_base &context);
// info for our compiler
template<class Signature>
struct wrapped_function {
using signature_t = Signature;
vm_external_function_type &external_func;
std::string_view name;
};
template<auto func>
consteval auto wrap(std::string_view name) {
return wrapped_function<std::decay_t<decltype(func)>>{
binding_wrapper<func>,
name
};
}
```
The most interesting part is inside `binding_wrapper<func>`. I won't show the full code here, because I still didn't tell about the VM architecture that will execute it. But in short binding_wrapper just checks the signature, generates some code that extracts arguments from VM, calls native functions and then puts the result back. Simple.
## The compiler and the VM
Maybe the most interesting part of the article. I have never written any compilers before (the thing I mentioned in the beginning of the article doesn't count), so I made it according to the first articles I found in Google.
Compiler has 3 modules:
- the lexer - splitting the code into tokens,
- the parser - building a tree from the tokens,
- the compiler itself - making the tree into byte-code. And doing semantic analysis at the same time (I was too lazy to make another module)
I think I could compose everything into one class via composition or smth, but it's too late already.
### Lexer
Primitive. We just look for tokens in a loop until we reach EOF.
```cpp
constexpr auto scan_token() -> std::optional<std::expected<lex_token, error_t>> {
char c = advance();
switch (c) {
case '{':
return make_token(lex_kind::kOpenBrace);
case '}':
return make_token(lex_kind::kCloseBrace);
case '(':
return make_token(lex_kind::kOpenParenthesis);
case ')':
// ...
case ' ':
case '\r':
case '\t':
// Ignore whitespace
return std::nullopt;
// ...
default:
if (is_digit(c)) {
return scan_number();
} else if (is_alpha(c)) {
return scan_identifier();
}
}
}
```
### Parser
More interesting. We need to build the AST (abstract syntax tree). And we need to store this tree somehow. The usual way with `Node` that keeps pointers to other nodes won't do, because we're at compile-time. I mean, we can write it this way, it will work, but extracting this tree into compile time? No. We would need serialisation or something. So we can use simple trick with `std::vector<Node>` and just make nodes store indices to each other.
This approach also increases the cache locality of the data for the CPU, but I doubt the CPU will be even aware of our "smart" trick, since everything is executed at compile-time.
The parser is recursive, while parsing one expression we parse another. Small fragment of the code:
```cpp
constexpr auto parse_statement() -> parse_result {
auto tok = peek();
if (!tok) return make_error("Unexpected end of input");
switch (tok->kind) {
case lex_kind::kOpenBrace: return parse_compound_stmt(); // { ... }
case lex_kind::kIf: return parse_if_statement(); // if (...) ...
case lex_kind::kWhile: return parse_while_statement(); //
"func", func,
"foo", foo
);
```
But why couldn't I make it work?
In C++ you can't pass a string into `template <auto ...args>`. We need `const_string`. We can't mix types in the one stream of variadic args and make compiler guess it right. Templates require explicitness and it's impossible to write a universal parser.
Variant #2 works, but you can't extract the function into the runtime. You just can't. Functions may have different signatures, but you need to make them all the same type, and create a FFI wrapper along the way. Compile-time doesn't allow `reinterpretet_cast<void*>(&func)`.
So I designed this:
```cpp
constexpr auto bindings = korka::make_bindings(
korka::wrap<fib>("cpp_fib"),
korka::wrap<print_n>("print_n")
);
```
Not so elegant, but still not bad.
`wrap` is very simple
```cpp
// our FFI signature
using vm_external_function_type = void(vm::context_base &context);
// info for our compiler
template<class Signature>
struct wrapped_function {
using signature_t = Signature;
vm_external_function_type &external_func;
std::string_view name;
};
template<auto func>
consteval auto wrap(std::string_view name) {
return wrapped_function<std::decay_t<decltype(func)>>{
binding_wrapper<func>,
name
};
}
```
The most interesting part is inside `binding_wrapper<func>`. I won't show the full code here, because I still didn't tell about the VM architecture that will execute it. But in short binding_wrapper just checks the signature, generates some code that extracts arguments from VM, calls native functions and then puts the result back. Simple.
## The compiler and the VM
Maybe the most interesting part of the article. I have never written any compilers before (the thing I mentioned in the beginning of the article doesn't count), so I made it according to the first articles I found in Google.
Compiler has 3 modules:
- the lexer - splitting the code into tokens,
- the parser - building a tree from the tokens,
- the compiler itself - making the tree into byte-code. And doing semantic analysis at the same time (I was too lazy to make another module)
I think I could compose everything into one class via composition or smth, but it's too late already.
### Lexer
Primitive. We just look for tokens in a loop until we reach EOF.
```cpp
constexpr auto scan_token() -> std::optional<std::expected<lex_token, error_t>> {
char c = advance();
switch (c) {
case '{':
return make_token(lex_kind::kOpenBrace);
case '}':
return make_token(lex_kind::kCloseBrace);
case '(':
return make_token(lex_kind::kOpenParenthesis);
case ')':
// ...
case ' ':
case '\r':
case '\t':
// Ignore whitespace
return std::nullopt;
// ...
default:
if (is_digit(c)) {
return scan_number();
} else if (is_alpha(c)) {
return scan_identifier();
}
}
}
```
### Parser
More interesting. We need to build the AST (abstract syntax tree). And we need to store this tree somehow. The usual way with `Node` that keeps pointers to other nodes won't do, because we're at compile-time. I mean, we can write it this way, it will work, but extracting this tree into compile time? No. We would need serialisation or something. So we can use simple trick with `std::vector<Node>` and just make nodes store indices to each other.
This approach also increases the cache locality of the data for the CPU, but I doubt the CPU will be even aware of our "smart" trick, since everything is executed at compile-time.
The parser is recursive, while parsing one expression we parse another. Small fragment of the code:
```cpp
constexpr auto parse_statement() -> parse_result {
auto tok = peek();
if (!tok) return make_error("Unexpected end of input");
switch (tok->kind) {
case lex_kind::kOpenBrace: return parse_compound_stmt(); // { ... }
case lex_kind::kIf: return parse_if_statement(); // if (...) ...
case lex_kind::kWhile: return parse_while_statement(); //
while (...) ...
case lex_kind::kReturn: return parse_return_statement(); // return ...;
default: return parse_expression_stmt(); /// ...;
}
}
constexpr auto parse_return_statement() -> parse_result {
if (!match(lex_kind::kReturn)) return make_error("Expected 'return'");
index_t expr_idx = empty_node; // empty_node = -1
if (auto next = peek(); next && next->kind != lex_kind::kSemicolon) {
auto expr = parse_expression(); // another recursive call
if (!expr) return std::unexpected{expr.error()};
expr_idx = *expr;
}
if (!match(lex_kind::kSemicolon)) return make_error("Expected ';' after return");
return m_pool.add(stmt_return{expr_idx});
}
```
parse_return_statement goes into parse_expression, that goes into parse_assigment, that goes into parse_logical_or, that goes... Well, you got it. That's how operator priority works here.
### Their Majesty Compiler (and analyser)
I may have cheated here a bit.
Before we even write a compiler, we must know for what architecture we do it. x86, ARM or even JVM.
Initially when I was working on a similar project, I planned to generate raw assembly for x86 (last versions of Clang and GCC support passing `constexpr std::string_view` into `asm(...)` statement), but honestly writing a compiler for a zoo of x86 instructions is the right way to madhouse.
And even so, if we downgrade our compiler we won't have nice constexpr asm anymore. And we can't also generate raw machine instructions because of DEP (data execution prevention). We'll have to call non-crossplatform `mmap` or `VirtualAlloc` to allocate some memory, copy the code there... Good riddance cross platform build compler, hello Windows Defender that will kill our app for such tricks with memory.
So where have I cheated? I made my own architecture that will execute inside a VM. A stack VM.
Why stack it? It turned out to be incredibly easy to generate the bytecode for. If you are doing a register architecture (as in processors or Lua), then you will have to write register allocation algorithms (it is difficult). And in the stack everything is much simpler.
If we need to sum A and B we just do this:
1. Put A into the stack.
2. Put B into the stack.
3. Execute sum instruction. It takes these two values and puts back their sum.
So I had this set of instructions at the end:
```cpp
enum class op_code : char {
// Loads/saves locals to/from the stack (variables).
lload, lsave,
i64_const, // Puts a constant onto the stack
// Math
i64_add, i64_sub, i64_mul, i64_div,
// Puts 1 if values are equal (i made <, <= later)
i64_cmp,
jmp, // jumps by offset
jmpz, // conditional jump by offset, only when 0 on the stack
call, // calls a function
ret, // returns from the function
trap, // calls a native C++ function
};
```
### So what about the analysis?
In classical compilers phases are strictly splitted: lexers builds tokens, parser builds tree, semantic analyser checks the types and variables, then optimisations, then codegen and then optimisations again.
As you can remember, I'm pretty lazy. And keep in mind that `constexpr` ops are not infinite. I didn't want to make a separate pipeline phase. So my compiler combines these two functions: semantic analysis and code generation.
They usually call it Single-Pass Compilation, but it's not really the case here, since it's only about these two phases. My compiler is a bit hybrid.
My compiler recursively walks the tree and does two things:
1. Checks the semantics: "was this variable declared and what's its type" before we even try to multiply something. Do function param types match? Does this function even exist? Etc.
2. Generates the byte-code. If semantics is ok, then we just write corresponding instructions immediately into the `std::vector<std::byte>` (the one we're going to elegantly extract via `to_array`).
And in the result we receive a ready, semantically-correct and absolute safe (let's pretend that I wrote the compiler bug-free, huh) byte-code that we feed to the
case lex_kind::kReturn: return parse_return_statement(); // return ...;
default: return parse_expression_stmt(); /// ...;
}
}
constexpr auto parse_return_statement() -> parse_result {
if (!match(lex_kind::kReturn)) return make_error("Expected 'return'");
index_t expr_idx = empty_node; // empty_node = -1
if (auto next = peek(); next && next->kind != lex_kind::kSemicolon) {
auto expr = parse_expression(); // another recursive call
if (!expr) return std::unexpected{expr.error()};
expr_idx = *expr;
}
if (!match(lex_kind::kSemicolon)) return make_error("Expected ';' after return");
return m_pool.add(stmt_return{expr_idx});
}
```
parse_return_statement goes into parse_expression, that goes into parse_assigment, that goes into parse_logical_or, that goes... Well, you got it. That's how operator priority works here.
### Their Majesty Compiler (and analyser)
I may have cheated here a bit.
Before we even write a compiler, we must know for what architecture we do it. x86, ARM or even JVM.
Initially when I was working on a similar project, I planned to generate raw assembly for x86 (last versions of Clang and GCC support passing `constexpr std::string_view` into `asm(...)` statement), but honestly writing a compiler for a zoo of x86 instructions is the right way to madhouse.
And even so, if we downgrade our compiler we won't have nice constexpr asm anymore. And we can't also generate raw machine instructions because of DEP (data execution prevention). We'll have to call non-crossplatform `mmap` or `VirtualAlloc` to allocate some memory, copy the code there... Good riddance cross platform build compler, hello Windows Defender that will kill our app for such tricks with memory.
So where have I cheated? I made my own architecture that will execute inside a VM. A stack VM.
Why stack it? It turned out to be incredibly easy to generate the bytecode for. If you are doing a register architecture (as in processors or Lua), then you will have to write register allocation algorithms (it is difficult). And in the stack everything is much simpler.
If we need to sum A and B we just do this:
1. Put A into the stack.
2. Put B into the stack.
3. Execute sum instruction. It takes these two values and puts back their sum.
So I had this set of instructions at the end:
```cpp
enum class op_code : char {
// Loads/saves locals to/from the stack (variables).
lload, lsave,
i64_const, // Puts a constant onto the stack
// Math
i64_add, i64_sub, i64_mul, i64_div,
// Puts 1 if values are equal (i made <, <= later)
i64_cmp,
jmp, // jumps by offset
jmpz, // conditional jump by offset, only when 0 on the stack
call, // calls a function
ret, // returns from the function
trap, // calls a native C++ function
};
```
### So what about the analysis?
In classical compilers phases are strictly splitted: lexers builds tokens, parser builds tree, semantic analyser checks the types and variables, then optimisations, then codegen and then optimisations again.
As you can remember, I'm pretty lazy. And keep in mind that `constexpr` ops are not infinite. I didn't want to make a separate pipeline phase. So my compiler combines these two functions: semantic analysis and code generation.
They usually call it Single-Pass Compilation, but it's not really the case here, since it's only about these two phases. My compiler is a bit hybrid.
My compiler recursively walks the tree and does two things:
1. Checks the semantics: "was this variable declared and what's its type" before we even try to multiply something. Do function param types match? Does this function even exist? Etc.
2. Generates the byte-code. If semantics is ok, then we just write corresponding instructions immediately into the `std::vector<std::byte>` (the one we're going to elegantly extract via `to_array`).
And in the result we receive a ready, semantically-correct and absolute safe (let's pretend that I wrote the compiler bug-free, huh) byte-code that we feed to the
1 calls
04.295 seconds
Submodules:
1> 141 ms MSBuild 16 calls
1> 775 ms SetModuleDependencies 10 calls
1> 1015 ms CL 2 calls
1> 1132 ms MultiToolTask 1 calls
03.427 seconds
The CL entry is for cpp files and it's 4.39x as fast as header-based. Great!
But it's the ixx dependency scanning and compilation (MultiToolTask) that brings things down. Things that aren't there with header-based.
MultiToolTask *is* parallelised though. Reducing thread count slows it down. And you can open up the msbuild binlog in the msbuild log viewer to see the parallelisation of ixx compilation. See which modules are on the end of the DAG slowing things down.
So, I don't know how MultiToolTask could be sped up, but, msbuild seems to be waiting for all ixx files before moving onto cpp files, so that's some parallelism left on the table.
Detailed timings of App:
Header-based, app pch:
1> 196 ms MSBuild 13 calls
1> 1000 ms Link 1 calls
1> 23270 ms CL 16 calls
24.708 seconds
Extlib modules + CommonStuff submodules:
1> 199 ms SetModuleDependencies 18 calls
1> 606 ms MSBuild 27 calls
1> 1197 ms Link 1 calls
1> 21877 ms CL 15 calls
24.078 seconds
Full submodules:
1> 459 ms MSBuild 27 calls
1> 1324 ms Link 1 calls
1> 4646 ms SetModuleDependencies 18 calls
1> 12593 ms MultiToolTask 1 calls
1> 49327 ms CL 15 calls
01:09.245 minutes
Slow. But looking at the log viewer, ixx compilation seems very well parallelised.
And 4.6s just to scan for dependencies. VS isn't launching a whole CL process for each file is it?
Also, why does CL take so long? All modules have been compiled by that point, so why would it be much slower?
Recompiling a single file from App:
Header-based, no pch:
1> 46 ms SetModuleDependencies 10 calls
1> 120 ms MSBuild 5 calls
1> 3757 ms CL 1 calls
04.095 seconds
Header-based, app pch:
1> 56 ms SetModuleDependencies 10 calls
1> 121 ms MSBuild 5 calls
1> 1793 ms CL 2 calls
02.059 seconds
Extlib + CommonStuff modules (as submodules):
1> 121 ms SetModuleDependencies 18 calls
1> 216 ms MSBuild 17 calls
1> 1793 ms CL 1 calls
02.162 seconds
Full submodules, except app:
1> 518 ms MSBuild 17 calls
1> 631 ms SetModuleDependencies 18 calls
1> 2211 ms CL 1 calls
03.095 seconds
Full submodules:
1> 559 ms MSBuild 17 calls
1> 696 ms SetModuleDependencies 18 calls
1> 1891 ms MultiToolTask 1 calls
1> 3221 ms CL 1 calls
06.331 seconds
That MultiToolTask is quite slow, checking that all the modules in the project are up to date it seems. Does it have to be this slow?
"CL.exe will run on 0 out of 224 file(s) in 224 batches. Startup
04.295 seconds
Submodules:
1> 141 ms MSBuild 16 calls
1> 775 ms SetModuleDependencies 10 calls
1> 1015 ms CL 2 calls
1> 1132 ms MultiToolTask 1 calls
03.427 seconds
The CL entry is for cpp files and it's 4.39x as fast as header-based. Great!
But it's the ixx dependency scanning and compilation (MultiToolTask) that brings things down. Things that aren't there with header-based.
MultiToolTask *is* parallelised though. Reducing thread count slows it down. And you can open up the msbuild binlog in the msbuild log viewer to see the parallelisation of ixx compilation. See which modules are on the end of the DAG slowing things down.
So, I don't know how MultiToolTask could be sped up, but, msbuild seems to be waiting for all ixx files before moving onto cpp files, so that's some parallelism left on the table.
Detailed timings of App:
Header-based, app pch:
1> 196 ms MSBuild 13 calls
1> 1000 ms Link 1 calls
1> 23270 ms CL 16 calls
24.708 seconds
Extlib modules + CommonStuff submodules:
1> 199 ms SetModuleDependencies 18 calls
1> 606 ms MSBuild 27 calls
1> 1197 ms Link 1 calls
1> 21877 ms CL 15 calls
24.078 seconds
Full submodules:
1> 459 ms MSBuild 27 calls
1> 1324 ms Link 1 calls
1> 4646 ms SetModuleDependencies 18 calls
1> 12593 ms MultiToolTask 1 calls
1> 49327 ms CL 15 calls
01:09.245 minutes
Slow. But looking at the log viewer, ixx compilation seems very well parallelised.
And 4.6s just to scan for dependencies. VS isn't launching a whole CL process for each file is it?
Also, why does CL take so long? All modules have been compiled by that point, so why would it be much slower?
Recompiling a single file from App:
Header-based, no pch:
1> 46 ms SetModuleDependencies 10 calls
1> 120 ms MSBuild 5 calls
1> 3757 ms CL 1 calls
04.095 seconds
Header-based, app pch:
1> 56 ms SetModuleDependencies 10 calls
1> 121 ms MSBuild 5 calls
1> 1793 ms CL 2 calls
02.059 seconds
Extlib + CommonStuff modules (as submodules):
1> 121 ms SetModuleDependencies 18 calls
1> 216 ms MSBuild 17 calls
1> 1793 ms CL 1 calls
02.162 seconds
Full submodules, except app:
1> 518 ms MSBuild 17 calls
1> 631 ms SetModuleDependencies 18 calls
1> 2211 ms CL 1 calls
03.095 seconds
Full submodules:
1> 559 ms MSBuild 17 calls
1> 696 ms SetModuleDependencies 18 calls
1> 1891 ms MultiToolTask 1 calls
1> 3221 ms CL 1 calls
06.331 seconds
That MultiToolTask is quite slow, checking that all the modules in the project are up to date it seems. Does it have to be this slow?
"CL.exe will run on 0 out of 224 file(s) in 224 batches. Startup
phase took 2040.9372ms."
Anyway.
Conclusion:
* I now have the data to know how I should go about modularising a codebase for build perf.
* Surprisingly, there is a middle-ground between 0% modules and 100% modules where you get optimal build performance. It seems extlibs and your common lib should be modularised and nothing else. Or maybe my internal lib headers are too small to benefit.
* Because of that, I might be able to have a header-based fallback for intellisense without it spreading to the rest of the code.
* Multiple modules > Partitions. Partitions have worse performance. I assume that's because they need to have an extra module at the end of the DAG.
* Their only advantage is shared module attachment across multiple ixx files, if you don't use `extern "C++"`. As I said before, I wish you could have "public" partitions or multiple modules with the same name attachment.
* MSVC partition cpp files are slightly faster vs module cpp files. But why. Cpp files wait for all ixx files to compile anyway. Noise in the data?
* MSBuild parallelises as it should, it seems, except that cpp files wait for all ixx files. Could improve performance by merging the tasks?
* cpp compilation can be much faster, but overall build perf brought down by ixx files and scanning.
* Moving implementation to ixx files doesn't always help. Need more data.
* And it would be ideal if build systems avoided the build cascade when only changing implementation details.
* The more modules you add to the solution, the more bloated the build system feels. Lots of scanning, lots of ixx checking. Can performance be improved?
* PCH can be beaten in some cases.
Problems:
* Intellisense. Red squiggles everywhere. Not only `import std` issues, but Intellisense is highly sensitive to errors in imported modules. It cannot limp along like it can with headers.
* A simple example would be missing a semicolon after a struct def in a header and in a module. Intellisense can still use the struct from the header, but not the module.
* Or in working code, something from `import std` that Intellisense can't handle.
* This means that parsing issues with Intellisense may be viral when using modules. Intellisense must either be perfect or tolerant.
* From a previous modularisation attempt, I removed the combination of explicit template instantiations of a class with constrained friend functions, due to ICE, which has now become a bogus compiler error. Bug not fixed.
* Lots of linker warnings from dllexport-ed manual RTTI data. Bug not fixed.
At least the compiler functions well enough to produce a working program with no further changes. That's pretty good.
https://redd.it/1va18lf
@r_cpp
Anyway.
Conclusion:
* I now have the data to know how I should go about modularising a codebase for build perf.
* Surprisingly, there is a middle-ground between 0% modules and 100% modules where you get optimal build performance. It seems extlibs and your common lib should be modularised and nothing else. Or maybe my internal lib headers are too small to benefit.
* Because of that, I might be able to have a header-based fallback for intellisense without it spreading to the rest of the code.
* Multiple modules > Partitions. Partitions have worse performance. I assume that's because they need to have an extra module at the end of the DAG.
* Their only advantage is shared module attachment across multiple ixx files, if you don't use `extern "C++"`. As I said before, I wish you could have "public" partitions or multiple modules with the same name attachment.
* MSVC partition cpp files are slightly faster vs module cpp files. But why. Cpp files wait for all ixx files to compile anyway. Noise in the data?
* MSBuild parallelises as it should, it seems, except that cpp files wait for all ixx files. Could improve performance by merging the tasks?
* cpp compilation can be much faster, but overall build perf brought down by ixx files and scanning.
* Moving implementation to ixx files doesn't always help. Need more data.
* And it would be ideal if build systems avoided the build cascade when only changing implementation details.
* The more modules you add to the solution, the more bloated the build system feels. Lots of scanning, lots of ixx checking. Can performance be improved?
* PCH can be beaten in some cases.
Problems:
* Intellisense. Red squiggles everywhere. Not only `import std` issues, but Intellisense is highly sensitive to errors in imported modules. It cannot limp along like it can with headers.
* A simple example would be missing a semicolon after a struct def in a header and in a module. Intellisense can still use the struct from the header, but not the module.
* Or in working code, something from `import std` that Intellisense can't handle.
* This means that parsing issues with Intellisense may be viral when using modules. Intellisense must either be perfect or tolerant.
* From a previous modularisation attempt, I removed the combination of explicit template instantiations of a class with constrained friend functions, due to ICE, which has now become a bogus compiler error. Bug not fixed.
* Lots of linker warnings from dllexport-ed manual RTTI data. Bug not fixed.
At least the compiler functions well enough to produce a working program with no further changes. That's pretty good.
https://redd.it/1va18lf
@r_cpp
Reddit
From the cpp community on Reddit
Explore this post and more from the cpp community
A clever branch free optimization
I'm the developer of memlz which is an extremely fast compression library.
We have `char* src, char* dst` for the source and destination buffers and `uint16_t flags` that we prepend bits to one at a time. The inner core looks something like this (pseudo code):
flags <<= 1;
uint64_t payload = ((uint64_t*)src)[i];
uint16_t hash_index = hash_function(payload);
if (hash_table[hash_index] == payload) {
flags |= 1;
*(uint16_t*)dst = (uint16_t)hash_index;
dst += sizeof(uint16_t);
}
else {
*(uint64_t*)dst = payload;
hash_table[hash_index] = payload;
dst += sizeof(uint64_t);
}
Depending on a hash comparison we need to output either 2 or 8 bytes, advance `dst` accordingly and prepend either a 1 or a 0 to `flags`.
Furthermore, at the end it's required that `hash_table[hash_index] == payload`, so we update `hash_table` in the false-case.
Let's benchmark it with 211 MB input so it's uncached:
memlz: 2744 MB/s
Now let's look at an amazing idea. The output to `*dst` can be rewritten with the ternary operator:
`*(uint64_t*)dst = hit ? hash_index : payload;`
That turns into a compare instruction (`cmp`) and a conditional move instruction (`cmove`) with no branching:
00007FF742A5A55B mov rax,r10
00007FF742A5A55E cmp rcx,r10
...
00007FF742A5A56D cmove rax,rdx
00007FF742A5A571 mov qword ptr [rdi],rax
The advancement of `dst` is also simple to make branchless, noting that `hit` will turn either 0 or 1:
uint64_t hit = (hash_table[hash_index] == payload);
dst += 8 - (hit * 6);
Now look at updating the `hash_table` where we update it to `payload` only if it differed from `payload`. What we can do is update it unconditionally at the end, and hope that the extra number of unnecessary writes to memory (where it just overwrites the same value) are not too expensive.
Final branch-free version:
uint64_t payload = ((uint64_t*)src)[i];
uint16_t hash_index = hash_function(payload);
flags <<= 1;
uint64_t hit = (hash_table[hash_index] == payload);
flags |= hit;
*(uint64_t*)dst = hit ? hash_index : payload;
hash_table[hash_index] = payload;
dst += 8 - (hit * 6);
Let's benchmark it:
memlz: 4269 MB/s
I had never believed such gains were possible because I had been micro-optimizing on this for weeks.
I later achieved 5070 MB/s. To put it in perspective, uncached memcpy runs at 14000 MB/s here and LZ4 - another popular fast compression library - at 718 MB/s.
https://redd.it/1wkuou2
@r_cpp
I'm the developer of memlz which is an extremely fast compression library.
We have `char* src, char* dst` for the source and destination buffers and `uint16_t flags` that we prepend bits to one at a time. The inner core looks something like this (pseudo code):
flags <<= 1;
uint64_t payload = ((uint64_t*)src)[i];
uint16_t hash_index = hash_function(payload);
if (hash_table[hash_index] == payload) {
flags |= 1;
*(uint16_t*)dst = (uint16_t)hash_index;
dst += sizeof(uint16_t);
}
else {
*(uint64_t*)dst = payload;
hash_table[hash_index] = payload;
dst += sizeof(uint64_t);
}
Depending on a hash comparison we need to output either 2 or 8 bytes, advance `dst` accordingly and prepend either a 1 or a 0 to `flags`.
Furthermore, at the end it's required that `hash_table[hash_index] == payload`, so we update `hash_table` in the false-case.
Let's benchmark it with 211 MB input so it's uncached:
memlz: 2744 MB/s
Now let's look at an amazing idea. The output to `*dst` can be rewritten with the ternary operator:
`*(uint64_t*)dst = hit ? hash_index : payload;`
That turns into a compare instruction (`cmp`) and a conditional move instruction (`cmove`) with no branching:
00007FF742A5A55B mov rax,r10
00007FF742A5A55E cmp rcx,r10
...
00007FF742A5A56D cmove rax,rdx
00007FF742A5A571 mov qword ptr [rdi],rax
The advancement of `dst` is also simple to make branchless, noting that `hit` will turn either 0 or 1:
uint64_t hit = (hash_table[hash_index] == payload);
dst += 8 - (hit * 6);
Now look at updating the `hash_table` where we update it to `payload` only if it differed from `payload`. What we can do is update it unconditionally at the end, and hope that the extra number of unnecessary writes to memory (where it just overwrites the same value) are not too expensive.
Final branch-free version:
uint64_t payload = ((uint64_t*)src)[i];
uint16_t hash_index = hash_function(payload);
flags <<= 1;
uint64_t hit = (hash_table[hash_index] == payload);
flags |= hit;
*(uint64_t*)dst = hit ? hash_index : payload;
hash_table[hash_index] = payload;
dst += 8 - (hit * 6);
Let's benchmark it:
memlz: 4269 MB/s
I had never believed such gains were possible because I had been micro-optimizing on this for weeks.
I later achieved 5070 MB/s. To put it in perspective, uncached memcpy runs at 14000 MB/s here and LZ4 - another popular fast compression library - at 718 MB/s.
https://redd.it/1wkuou2
@r_cpp
Reddit
From the cpp community on Reddit
Explore this post and more from the cpp community
EDG C++ fronted now released as open source
https://edgcpp.org/#transition
https://redd.it/1wudtq0
@r_cpp
https://edgcpp.org/#transition
https://redd.it/1wudtq0
@r_cpp
EDGCPP
Open Source Transition
On September 30, 2026, EDG's C++ front end went open source, with The C++ Alliance as its nonprofit home. What changes for EDG users, how to contribute, and where to follow the work.
std::variant, operator== and pattern matching
I was thinking, wouldn't adding equality comparison support between `std::variant` and one of its unambiguous alternatives help simplify potential pattern matching designs?
For example, imagine something like this (hypothetical syntax):
std::variant<int, std::string> v = 42;
match (v) {
case 42 => handle_int();
case "hello" => handle_string();
case _ => handle_other();
}
The idea would be to take advantage of something C++ already has: `operator==`. At the end of the day, matching is fundamentally a comparison, so why not build on the existing equality semantics?
For `std::optional`, we can get this with its existing comparison operators and the most trivial pattern matching compiler support:
std::optional<int> o = 42;
match (o) {
case 42 => handle_value();
case std::nullopt => handle_empty();
case _ => handle_other();
}
// Which would translate to:
if (o == 42)
handle_value();
else if (o == nullopt)
handle_empty();
else
handle_other();
And if we had something like `std::match_projection<Subject, Pattern>`, we could also extract the actual matched value instead of having to manually call `std::get`, dereference an optional, etc.
Basically, after a successful comparison, `match_projection` would tell the compiler what to extract based on the subject and pattern types and we could optionally bind that value using something like a `as <declaration>` syntax.
For example:
std::optional<int> o = 42;
std::optional<int> other_opt = 42;
match (o) {
// No binding needed
case 42 => foo();
// match_projection<optional<int>, int> -> int&
case 42 as int& x => use(x);
// match_projection<optional<int>, nullopt_t> -> void
case std::nullopt => handle_empty();
// match_projection<optional<int>, optional<int>>
// -> optional<int>&
case other_opt as auto& x => use(x);
}
The same would apply to `std::variant`, assuming we also extend its `operator==` to support comparisons with individual alternatives:
match (v) {
case 42 as int& x => use(x);
case "hello" as std::string& s => use(s);
// Only need to define operator== for this helper for this to work
case indexed<0> => handle_any_int();
// Or under this form for the sake of disambiguation
case indexed<0>(10) => handle_ten();
// Also provide match_projection<indexed<0>> to enable binding
case indexed<0>(20) as int& x => use(x);
case _ => handle_other();
}
Here, `indexed<>` would just be a hypothetical helper for explicitly selecting which alternative to compare against. It would only need an appropriate `operator==` to work with matching, and a corresponding `match_projection` specialization if we also wanted to extract the alternative.
This way, the matching itself wouldn't need to know anything about `variant`, `optional` or even user-defined types. It would just use their equality operators, while `match_projection` would tell it what to extract when we actually want to bind something, which is just syntactic sugar.
I'm curious what you think about this approach. It feels like we could get quite a bit of useful pattern matching functionality without introducing too much new language machinery or convoluted new language traits and APIs.
Also do you think std::variant being equality comparable with instances of its alternatives would be an useful addition on its own?
std::variant<int, std::string> v = 42;
if (v == "not my string") ...
// Which is simpler than
if (std::holds_alternative<std::string>(v) && std::get<std::string>(v) == "not my string") ...
Syntax seems nice on its own...
https://redd.it/1x1wh77
@r_cpp
I was thinking, wouldn't adding equality comparison support between `std::variant` and one of its unambiguous alternatives help simplify potential pattern matching designs?
For example, imagine something like this (hypothetical syntax):
std::variant<int, std::string> v = 42;
match (v) {
case 42 => handle_int();
case "hello" => handle_string();
case _ => handle_other();
}
The idea would be to take advantage of something C++ already has: `operator==`. At the end of the day, matching is fundamentally a comparison, so why not build on the existing equality semantics?
For `std::optional`, we can get this with its existing comparison operators and the most trivial pattern matching compiler support:
std::optional<int> o = 42;
match (o) {
case 42 => handle_value();
case std::nullopt => handle_empty();
case _ => handle_other();
}
// Which would translate to:
if (o == 42)
handle_value();
else if (o == nullopt)
handle_empty();
else
handle_other();
And if we had something like `std::match_projection<Subject, Pattern>`, we could also extract the actual matched value instead of having to manually call `std::get`, dereference an optional, etc.
Basically, after a successful comparison, `match_projection` would tell the compiler what to extract based on the subject and pattern types and we could optionally bind that value using something like a `as <declaration>` syntax.
For example:
std::optional<int> o = 42;
std::optional<int> other_opt = 42;
match (o) {
// No binding needed
case 42 => foo();
// match_projection<optional<int>, int> -> int&
case 42 as int& x => use(x);
// match_projection<optional<int>, nullopt_t> -> void
case std::nullopt => handle_empty();
// match_projection<optional<int>, optional<int>>
// -> optional<int>&
case other_opt as auto& x => use(x);
}
The same would apply to `std::variant`, assuming we also extend its `operator==` to support comparisons with individual alternatives:
match (v) {
case 42 as int& x => use(x);
case "hello" as std::string& s => use(s);
// Only need to define operator== for this helper for this to work
case indexed<0> => handle_any_int();
// Or under this form for the sake of disambiguation
case indexed<0>(10) => handle_ten();
// Also provide match_projection<indexed<0>> to enable binding
case indexed<0>(20) as int& x => use(x);
case _ => handle_other();
}
Here, `indexed<>` would just be a hypothetical helper for explicitly selecting which alternative to compare against. It would only need an appropriate `operator==` to work with matching, and a corresponding `match_projection` specialization if we also wanted to extract the alternative.
This way, the matching itself wouldn't need to know anything about `variant`, `optional` or even user-defined types. It would just use their equality operators, while `match_projection` would tell it what to extract when we actually want to bind something, which is just syntactic sugar.
I'm curious what you think about this approach. It feels like we could get quite a bit of useful pattern matching functionality without introducing too much new language machinery or convoluted new language traits and APIs.
Also do you think std::variant being equality comparable with instances of its alternatives would be an useful addition on its own?
std::variant<int, std::string> v = 42;
if (v == "not my string") ...
// Which is simpler than
if (std::holds_alternative<std::string>(v) && std::get<std::string>(v) == "not my string") ...
Syntax seems nice on its own...
https://redd.it/1x1wh77
@r_cpp
Reddit
From the cpp community on Reddit
Explore this post and more from the cpp community
Which API design should my framework have?
right now in vexa(my game/graphics library) how you initialize window with a renderer is rather straightforward:
```cpp
\#include <vexa/vexa.hpp>
using namespace vexa;
int main()
{
Engine::Init(Engine::VIDEO);
Window window = Window().setSize({1280, 720}).setRenderer({}).create();
// ...
```
YES, it uses builder pattern, not very C++-ish but i like it.
However, there are two problems with it.
first one is that usually you have builder struct building to target type so that you dont need something like `.create()` that creates classic `if (m_created) ...` problem a.k.a two phase construction. but bigger problem that caused me two want to switch to this API style is about memory management. and it is now C++'s problem.. Even rust cant handle it, because this is what you tell it to do.
so lets dont talk too much:
```cpp
Engine::Init(Engine::FONT); // calls `TTF_Init();` by SDL_TTF behind the scenes
Font font = Font::Load("...");
...
Engine::Quit();
```
A Font has destructor running on scope exit. which means before font object gets destroyed on '}' Engine::Quit() so TTF_Quit() runs. You see, when Font object gets unloaded at scope end the subsystem is not live anymore, we get a segfault. to fix this i've made Engine have a Guard struct which does Engine::Quit() automatically. But then decided that this is not i want for my API. I would priorotize explicitness for the master deinitialization.
to fix this im thinking of new API design style:
```cpp
Window window = Engine::BuildWindow().setSize({1280, 720}).setRenderer().create();
```
where BuildWindow() returns WindowBuilder not a Window, unlike the previous(so bad) choice.
for fonts, as you might already guess:
```cpp
Font font = Engine::LoadFont("...");
```
which creates a font and returns reference to it, resulting Engine to know about font count and Quit or not based on that.
code: https://github.com/monjaris/vexa
https://redd.it/1x8gtg7
@r_cpp
right now in vexa(my game/graphics library) how you initialize window with a renderer is rather straightforward:
```cpp
\#include <vexa/vexa.hpp>
using namespace vexa;
int main()
{
Engine::Init(Engine::VIDEO);
Window window = Window().setSize({1280, 720}).setRenderer({}).create();
// ...
```
YES, it uses builder pattern, not very C++-ish but i like it.
However, there are two problems with it.
first one is that usually you have builder struct building to target type so that you dont need something like `.create()` that creates classic `if (m_created) ...` problem a.k.a two phase construction. but bigger problem that caused me two want to switch to this API style is about memory management. and it is now C++'s problem.. Even rust cant handle it, because this is what you tell it to do.
so lets dont talk too much:
```cpp
Engine::Init(Engine::FONT); // calls `TTF_Init();` by SDL_TTF behind the scenes
Font font = Font::Load("...");
...
Engine::Quit();
```
A Font has destructor running on scope exit. which means before font object gets destroyed on '}' Engine::Quit() so TTF_Quit() runs. You see, when Font object gets unloaded at scope end the subsystem is not live anymore, we get a segfault. to fix this i've made Engine have a Guard struct which does Engine::Quit() automatically. But then decided that this is not i want for my API. I would priorotize explicitness for the master deinitialization.
to fix this im thinking of new API design style:
```cpp
Window window = Engine::BuildWindow().setSize({1280, 720}).setRenderer().create();
```
where BuildWindow() returns WindowBuilder not a Window, unlike the previous(so bad) choice.
for fonts, as you might already guess:
```cpp
Font font = Engine::LoadFont("...");
```
which creates a font and returns reference to it, resulting Engine to know about font count and Quit or not based on that.
code: https://github.com/monjaris/vexa
https://redd.it/1x8gtg7
@r_cpp
GitHub
GitHub - monjaris/vexa: Modern cross-platform game/graphics framework written in C++23
Modern cross-platform game/graphics framework written in C++23 - monjaris/vexa
The intention and spirit behind modules seem diametrically opposed to their actual implementations by compiler toolchains.
The lynchpin of C++ modules is the built module interface (BMI). Each BMI is meant to be a lightweight data structure representing the syntax of a module unit (comprised of one primary module interface and potentially one or more partitions), with approximately O(1) complexity of symbol lookup. This massively accelerates repeated lookups into the same translation unit, and avoids paying the cost of a full preprocessor run and front-end lex + parse, as might otherwise happen with header files. In this way both the first clean build, and incremental builds are considerably accelerated and made much more efficient—build the BMI once, reuse it across future compiles, and we don't need large core counts and massively parallel jobs because the BMI is now available afterwards.
However, the way compiler toolchains have actually implemented them seems diametrically opposed to this goal of fast lookup. Today, BMIs are highly sensitive to any change in the command-line invocation of the compiler/dependency scanning tool, including the C++ version, warning and feature flags, and especially macro definitions, with
BMIs are considered implementation details, and aren't even stable across compiler versions within the same toolchain. Compare to object files, where something compiled by really old versions can still be used on newer versions without too much fuss. This, from the user's perspective, entirely defeats that design ideal mentioned above: fast repeated lookups. Consider a simple example: a certain module uses a project-specific macro representing the platform, to change several function signatures. This module is now precompiled thrice, once each for
I believe that macros and the preprocessor are highly problematic. However, their very limitations are also an advantage here: their effect on code collapses to completely binary decisions. A macro is either defined or not, and a macro is either in the set of accepted values, or it isn't (e.g.
This would make things like library feature configuration with macros really straightforward—specify the macros one wants for that feature at the command-line, which is enshrined in build system code rather than source code—the BMI can be reused, done.
Now, the compiler and C++ standard are a lot harder as these probably affect the internal state of the compiler rather than merely the value of
As mentioned above, build systems are also forced into this rather inefficient model to accommodate compiler behaviour. CMake in its latest
The lynchpin of C++ modules is the built module interface (BMI). Each BMI is meant to be a lightweight data structure representing the syntax of a module unit (comprised of one primary module interface and potentially one or more partitions), with approximately O(1) complexity of symbol lookup. This massively accelerates repeated lookups into the same translation unit, and avoids paying the cost of a full preprocessor run and front-end lex + parse, as might otherwise happen with header files. In this way both the first clean build, and incremental builds are considerably accelerated and made much more efficient—build the BMI once, reuse it across future compiles, and we don't need large core counts and massively parallel jobs because the BMI is now available afterwards.
However, the way compiler toolchains have actually implemented them seems diametrically opposed to this goal of fast lookup. Today, BMIs are highly sensitive to any change in the command-line invocation of the compiler/dependency scanning tool, including the C++ version, warning and feature flags, and especially macro definitions, with
-DMACRO or /DMACRO. This means that changing just one flag is likely to cause a BMI cache miss and a full BMI reconstruction, which can be fairly slow for larger modules (like module std).BMIs are considered implementation details, and aren't even stable across compiler versions within the same toolchain. Compare to object files, where something compiled by really old versions can still be used on newer versions without too much fuss. This, from the user's perspective, entirely defeats that design ideal mentioned above: fast repeated lookups. Consider a simple example: a certain module uses a project-specific macro representing the platform, to change several function signatures. This module is now precompiled thrice, once each for
-DFOO_WINDOWS, -DFOO_DARWIN, -DFOO_LINUX, instead of just once.I believe that macros and the preprocessor are highly problematic. However, their very limitations are also an advantage here: their effect on code collapses to completely binary decisions. A macro is either defined or not, and a macro is either in the set of accepted values, or it isn't (e.g.
#if __cplusplus >= 202603L). The preprocessor state might change throughout the source code of a translation unit, but the entire set of possible states can be enumerated in finite and reasonably short time at compile time—otherwise the front-end would never complete its work. To me, this seems like the preprocessor and parser could enumerate all possible preprocessor states of the source code, and stamp out both possibilities for each macro switch in the BMI; during lookup, the compiler can select the correct code path depending on what is provided at that particular invocation (not code definitions, but command-line invocations, as this would break the module assurance that macros do not leak into BMIs from consumers, nor do consumers see macros from a BMI). This would make things like library feature configuration with macros really straightforward—specify the macros one wants for that feature at the command-line, which is enshrined in build system code rather than source code—the BMI can be reused, done.
Now, the compiler and C++ standard are a lot harder as these probably affect the internal state of the compiler rather than merely the value of
__cplusplus; however, I genuinely feel like there really ought to be a better way forward, especially if C++ is to continue as a 'source may not be available' language. This discussion is moot if we always want to compile from source, but I want to say that is wasteful, and another driving force of the modules feature was to do away with wasteful and repeated recomputation of the same thing.As mentioned above, build systems are also forced into this rather inefficient model to accommodate compiler behaviour. CMake in its latest
iteration, for instance, has a notion of 'BMI compatibility', and probably does some sort of set manipulation on compile flags to determine if another BMI for the same module interface is needed or not, based on how it is
I'm sure I don't have the entire picture as I am not a compiler front-end developer, and I don't mean to sound impertinent here, the effort put into delivering modules has been huge. However there are some decisions made which, as modules user and advocate, seem a little contradictory to the spirit of modules. I've written this after some thought on the situation and I'm interested in hearing from the community and compiler front-end developers who have worked on modules on my thoughts above.
Cheers.
https://redd.it/1x9famy
@r_cpp
imported. Why? This shouldn't be the case, a BMI really ought to be widely (if not universally) compatible, regardless of what flags go in the command-line. I'm sure I don't have the entire picture as I am not a compiler front-end developer, and I don't mean to sound impertinent here, the effort put into delivering modules has been huge. However there are some decisions made which, as modules user and advocate, seem a little contradictory to the spirit of modules. I've written this after some thought on the situation and I'm interested in hearing from the community and compiler front-end developers who have worked on modules on my thoughts above.
Cheers.
https://redd.it/1x9famy
@r_cpp
Reddit
From the cpp community on Reddit
Explore this post and more from the cpp community
Pain of making a native GUI in cpp
So I just wanted to vent about the absolute pain of making a working gui in cpp, I am working on a scientific project to make an openFOAM gui and browse openFOAM code to add TENO schemes to it from scientific papers such as Fu et al and working through the binaries.
I have not used AI in this project because CFD is very delicate and quite frankly, AI is not ready for such complexity - especially numerical schemes such as TENO, I ended up writing the meshing, topological code and mathematics myself and by far, the hardest part was the gui coordinates and memory management. I wanted to PULL MY HAIR OUT because of managing segfaults, crashes because of a random pointer hidden inside a 2000 line function, I had to also manage internal functions of openfoam(and you know how that goes), boundary conditions, and mesh topology, it was driving me nuts. I generally regard myself as fluent in programming languages such as cpp, python, rust etc, but this is a whole nother level data management.
in the end it turned out to be a pretty good contribution to the openFOAM community, hopefully the project will mature further and I will be able to write a paper on it.
https://redd.it/1xezb1k
@r_cpp
So I just wanted to vent about the absolute pain of making a working gui in cpp, I am working on a scientific project to make an openFOAM gui and browse openFOAM code to add TENO schemes to it from scientific papers such as Fu et al and working through the binaries.
I have not used AI in this project because CFD is very delicate and quite frankly, AI is not ready for such complexity - especially numerical schemes such as TENO, I ended up writing the meshing, topological code and mathematics myself and by far, the hardest part was the gui coordinates and memory management. I wanted to PULL MY HAIR OUT because of managing segfaults, crashes because of a random pointer hidden inside a 2000 line function, I had to also manage internal functions of openfoam(and you know how that goes), boundary conditions, and mesh topology, it was driving me nuts. I generally regard myself as fluent in programming languages such as cpp, python, rust etc, but this is a whole nother level data management.
in the end it turned out to be a pretty good contribution to the openFOAM community, hopefully the project will mature further and I will be able to write a paper on it.
https://redd.it/1xezb1k
@r_cpp
arXiv.org
A class of new high-order finite-volume TENO schemes for...
The recently proposed high-order TENO scheme [Fu et al., Journal of Computational Physics, 305, pp.333-359] has shown great potential in predicting complex fluids owing to the novel weighting...
How do I avoid UB in contracts?
This question might be better served in /r/cpp_questions but since contracts were the reason C++26 failed the latest vote I thought posting it here might generate some useful debate.
I've been using contracts in personal projects since GCC16 was released. I've come to appreciate them both as documentation and in bug-finding. After the recent controversial vote I did have another look at them and their use in my code. Most of my contracts looks like the example in "3.5.5 Consecutive and Repeated Evaluations" of p2900:
```
void f(int *p)
pre( p != nullptr ) // precondition #1
pre( *p > 0 ); // precondition #2
```
This works as expected in `enforce`, `quick-enforce` and `ignore` evaluations. However if I use `observe` evaluation it'll crash with UB on the second precondition.
One fix is to merge the preconditions together `pre( p != nullptr && *p > 0)` which works in this case, but doesn't scale to for example classes where you'll have `pre( p != nullptr)` on the constructor and then assume it's valid for the rest of the body.
Another solution is to never use `observe` evaluation. This works in my applications where I control the build, but doesn't work in libraries used by others where I don't.
I wonder what my options here are?
*Edit* [Godbolt link](https://godbolt.org/z/c34bGabnf)
https://redd.it/1xk6lwk
@r_cpp
This question might be better served in /r/cpp_questions but since contracts were the reason C++26 failed the latest vote I thought posting it here might generate some useful debate.
I've been using contracts in personal projects since GCC16 was released. I've come to appreciate them both as documentation and in bug-finding. After the recent controversial vote I did have another look at them and their use in my code. Most of my contracts looks like the example in "3.5.5 Consecutive and Repeated Evaluations" of p2900:
```
void f(int *p)
pre( p != nullptr ) // precondition #1
pre( *p > 0 ); // precondition #2
```
This works as expected in `enforce`, `quick-enforce` and `ignore` evaluations. However if I use `observe` evaluation it'll crash with UB on the second precondition.
One fix is to merge the preconditions together `pre( p != nullptr && *p > 0)` which works in this case, but doesn't scale to for example classes where you'll have `pre( p != nullptr)` on the constructor and then assume it's valid for the rest of the body.
Another solution is to never use `observe` evaluation. This works in my applications where I control the build, but doesn't work in libraries used by others where I don't.
I wonder what my options here are?
*Edit* [Godbolt link](https://godbolt.org/z/c34bGabnf)
https://redd.it/1xk6lwk
@r_cpp
godbolt.org
Compiler Explorer - C++ (x86-64 gcc 16.1)
int charges = 0;
struct Money {
int cents{};
};
// Charge an order once. The postcondition says exactly one charge happened.
void charge(Money* cents)
pre(cents != nullptr)
pre(cents->cents > 0)
{
if (cents) cents->cents++;
}
int main()…
struct Money {
int cents{};
};
// Charge an order once. The postcondition says exactly one charge happened.
void charge(Money* cents)
pre(cents != nullptr)
pre(cents->cents > 0)
{
if (cents) cents->cents++;
}
int main()…
Catastrophic misoptimization of byte-range equality comparison in all major C++ compilers (and Rust). Language issue or compiler issue?
Someone brought a C++ snippet that reduced to the following (std::array used instead of char* for consistency for later)
bool eq2(const std::array<char, 64>& lhs, const std::array<char, 64>& rhs) {
for (int i = 0; i < 64; ++i)
if (lhs[i] != rhs[i])
return false;
return true;
}
It basically returns true iff two 64 byte memory regions are a bitwise match. You'd think this can be optimized by modern compilers flawlessly, right? Right?! And the worst thing that can happen is it doesn't get autovectorized, right? Right?!
Well, to everybody's surprise... https://godbolt.org/z/v4d8G5ovh
GCC attempts to partially conditionally vectorize but doesn't want to use unaligned loads. Moreover its vectorization is way more cumbersome than it needs to be. Then after it finds a mismatch it... reverts to the unvectorized version?! Clang and MSVC do not even attempt to vectorize it - and in a way it makes them end up better than GCC, which is wild.
----------------
Now, to try to investigate we've checked how it looks in Rust. https://godbolt.org/z/K7xE3qc94. It does what GCC does but fully vectorized.
At this point we're confused as to what the source of the problem is. Are we missing something with respect to what transformations are allowed? Is it really that much to ask from the as-if rule?
As a sanity check we use std::array's operator==. https://godbolt.org/z/xPhPYMjvz. Oh would you look at that? Now the compilers can do well (ok not you MSVC. GCC also fumbles the flag register slightly). The situation is the same in Rust - https://godbolt.org/z/3GjWorze8. Not only does it vectorize correctly but the vectorized code is better - using vpxor.
-----------------
Ultimately this isn't just academical. Situations like this undermine the trust in the compiler at the most fundamental level. Not every place can use std::array, not everyone can use ranges and span yet. We could use `std::equal` but why does it matter so much? What if `!=` changes to `<` and there's no good solution anymore? To what degree are we supposed to be paranoid about basic optimizations being done or not?
The similarity of codegen between Rust and C++ would point to it being either a compiler issue or a fundamental code correctness issue. The fact that C++ Clang differs from Rust (LLVM) would suggest it's at least partially a language issue. Why is this extremely simple code so nasty?
https://redd.it/1xlyti8
@r_cpp
Someone brought a C++ snippet that reduced to the following (std::array used instead of char* for consistency for later)
bool eq2(const std::array<char, 64>& lhs, const std::array<char, 64>& rhs) {
for (int i = 0; i < 64; ++i)
if (lhs[i] != rhs[i])
return false;
return true;
}
It basically returns true iff two 64 byte memory regions are a bitwise match. You'd think this can be optimized by modern compilers flawlessly, right? Right?! And the worst thing that can happen is it doesn't get autovectorized, right? Right?!
Well, to everybody's surprise... https://godbolt.org/z/v4d8G5ovh
GCC attempts to partially conditionally vectorize but doesn't want to use unaligned loads. Moreover its vectorization is way more cumbersome than it needs to be. Then after it finds a mismatch it... reverts to the unvectorized version?! Clang and MSVC do not even attempt to vectorize it - and in a way it makes them end up better than GCC, which is wild.
----------------
Now, to try to investigate we've checked how it looks in Rust. https://godbolt.org/z/K7xE3qc94. It does what GCC does but fully vectorized.
At this point we're confused as to what the source of the problem is. Are we missing something with respect to what transformations are allowed? Is it really that much to ask from the as-if rule?
As a sanity check we use std::array's operator==. https://godbolt.org/z/xPhPYMjvz. Oh would you look at that? Now the compilers can do well (ok not you MSVC. GCC also fumbles the flag register slightly). The situation is the same in Rust - https://godbolt.org/z/3GjWorze8. Not only does it vectorize correctly but the vectorized code is better - using vpxor.
-----------------
Ultimately this isn't just academical. Situations like this undermine the trust in the compiler at the most fundamental level. Not every place can use std::array, not everyone can use ranges and span yet. We could use `std::equal` but why does it matter so much? What if `!=` changes to `<` and there's no good solution anymore? To what degree are we supposed to be paranoid about basic optimizations being done or not?
The similarity of codegen between Rust and C++ would point to it being either a compiler issue or a fundamental code correctness issue. The fact that C++ Clang differs from Rust (LLVM) would suggest it's at least partially a language issue. Why is this extremely simple code so nasty?
https://redd.it/1xlyti8
@r_cpp
godbolt.org
Compiler Explorer - C++
bool eq2(const std::array<char, 64>& lhs, const std::array<char, 64>& rhs) {
for (int i = 0; i < 64; ++i)
if (lhs[i] != rhs[i])
return false;
return true;
}
for (int i = 0; i < 64; ++i)
if (lhs[i] != rhs[i])
return false;
return true;
}
Is loop unrolling one of the speed booster
Long story short, I tried to check performance of C++ vs python by checking if file exists.
Here after - naive loop unrolling, seems the C++ code speed boosted. Please suggest other hacks/suggestions to make C++ run faster. Also if any books, links, github - please. I request C++ professionals
## Python time taken
C++ default build, time taken
Default compilation was slower than python, but after adding "Release" flag on, the CMake generated build, faster by
Now the final part
The final version is faster by
when measured by
https://redd.it/1xnoq3m
@r_cpp
Long story short, I tried to check performance of C++ vs python by checking if file exists.
Here after - naive loop unrolling, seems the C++ code speed boosted. Please suggest other hacks/suggestions to make C++ run faster. Also if any books, links, github - please. I request C++ professionals
import os.path
FILES_DIRECTORY : str = "data"
def missing_parser(_skip_index: int, _max_limit : int = 400):
_cur_index : int = _skip_index
_max_limit = _skip_index + 400
while _cur_index < _max_limit:
for j in range(_cur_index, _cur_index+100):
if os.path.exists(os.path.join(FILES_DIRECTORY, str(j)+".pkl")):
print("Path exists",str(j)+".pkl")
else:
print("Missing ",str(j)+".pkl")
_cur_index += 100
missing_parser(1)
## Python time taken
real 0m0.750s
user 0m0.011s
sys 0m0.108s
#include<iostream>
#include<fstream>
#include<string>
#include<filesystem>
#define FILE_DIRECTORY = "data"
void check_files(unsigned _start, unsigned _end){
std::string file_name;
for(unsigned k=_start; k<=_end; k++){
bool file_exists = false;
std::string filename = "./data/"+std::to_string(k)+".pkl";
file_exists = std::filesystem::exists(filename);
if(file_exists){
std::cout<<"File Exists\n";
}else{
std::cout<<"File not exists\n";
}
}
}
int main(int argc, char const *argv[]){
check_files(1, 400);
return 0;
}
C++ default build, time taken
real 0m0.706s
user 0m0.004s
sys 0m0.080s
Default compilation was slower than python, but after adding "Release" flag on, the CMake generated build, faster by
0.10 seconds. Now the final part
#include<iostream>
#include<fstream>
#include<string>
#include<filesystem>
#define FILE_DIRECTORY = "data"
void check_files(unsigned _start, unsigned _end){
std::string file_name;
for(unsigned k=_start; k<=(_end/10)+1; k++){
bool file_exists[10] = {0};
std::string filename1 = "./data/"+std::to_string(k)+".pkl";
std::string filename2 = "./data/"+std::to_string(k+1)+".pkl";
std::string filename3 = "./data/"+std::to_string(k+2)+".pkl";
std::string filename4 = "./data/"+std::to_string(k+3)+".pkl";
std::string filename5 = "./data/"+std::to_string(k+4)+".pkl";
std::string filename6 = "./data/"+std::to_string(k+5)+".pkl";
std::string filename7 = "./data/"+std::to_string(k+6)+".pkl";
std::string filename8 = "./data/"+std::to_string(k+7)+".pkl";
std::string filename9 = "./data/"+std::to_string(k+8)+".pkl";
std::string filename10 = "./data/"+std::to_string(k+9)+".pkl";
file_exists[k] = std::filesystem::exists(filename1);
file_exists[k+1] = std::filesystem::exists(filename2);
file_exists[k+2] = std::filesystem::exists(filename3);
file_exists[k+3] = std::filesystem::exists(filename4);
file_exists[k+4] = std::filesystem::exists(filename5);
file_exists[k+5] = std::filesystem::exists(filename6);
file_exists[k+6] = std::filesystem::exists(filename7);
file_exists[k+7] = std::filesystem::exists(filename8);
file_exists[k+8] = std::filesystem::exists(filename9);
file_exists[k+9] = std::filesystem::exists(filename10);
if(file_exists[k]){
std::cout<<k<<"File Exists\n";
}else{
std::cout<<"File not exists\n";
}
if(file_exists[k+1]){
std::cout<<k<<"File Exists\n";
}else{
std::cout<<"File not exists\n";
}
if(file_exists[k+2]){
std::cout<<k<<"File Exists\n";
}else{
std::cout<<"File not exists\n";
}
if(file_exists[k+3]){
std::cout<<k<<"File Exists\n";
}else{
std::cout<<"File not exists\n";
}
//so on, removed due to code length
}
}
int main(int argc, char const *argv[]){
check_files(1, 400);
return 0;
}
The final version is faster by
0.2 second. when measured by
$ time command, real 0m0.512s
user 0m0.000s
sys 0m0.055s
https://redd.it/1xnoq3m
@r_cpp
Reddit
From the cpp community on Reddit
Explore this post and more from the cpp community
On the scale of 1-10, am I cooked?
I took "How solid are your C++ fundamentals?", a quiz written by Mateusz Pusz, author of mp-units. I scored 42%, which put me higher than 54% of the 349 people who had taken it so far.
Some context:
🔹 I'm a 3rd-semester CS student at Abdul Wali Khan University, Mardan.
🔹 I have no internship, no job, and zero professional C++ experience.
🔹 The topics this quiz covers (the ODR, value categories, exception-safety guarantees, argument-dependent lookup) were never part of my coursework. I learned C++ on my own over 3 years of grinding, with no mentor and no one guiding me.
🔹 For the last 1.5 years I haven't written much meaningful C++ beyond uni lab sessions. I've been focused on Linux and building my own workflow and desktop environment around Hyprland.
My breakdown:
• Objects in memory: 58%
• The type system: 52%
• Functions and safety: 30%
• Names and language plumbing: 27%
Give it a try: https://train-it.eu/quiz/how-solid-are-your-cpp-fundamentals/
https://redd.it/1xo4ebp
@r_cpp
I took "How solid are your C++ fundamentals?", a quiz written by Mateusz Pusz, author of mp-units. I scored 42%, which put me higher than 54% of the 349 people who had taken it so far.
Some context:
🔹 I'm a 3rd-semester CS student at Abdul Wali Khan University, Mardan.
🔹 I have no internship, no job, and zero professional C++ experience.
🔹 The topics this quiz covers (the ODR, value categories, exception-safety guarantees, argument-dependent lookup) were never part of my coursework. I learned C++ on my own over 3 years of grinding, with no mentor and no one guiding me.
🔹 For the last 1.5 years I haven't written much meaningful C++ beyond uni lab sessions. I've been focused on Linux and building my own workflow and desktop environment around Hyprland.
My breakdown:
• Objects in memory: 58%
• The type system: 52%
• Functions and safety: 30%
• Names and language plumbing: 27%
Give it a try: https://train-it.eu/quiz/how-solid-are-your-cpp-fundamentals/
https://redd.it/1xo4ebp
@r_cpp
Train IT
How solid are your C++ fundamentals? | Train IT
If you have ever answered a junior's C++ question and later wondered whether your answer was actually right, this is the honest way to find out. A hard self-check on the C++ fundamentals senior engineers are assumed to know but rarely learned properly. Your…
Dealing with AI Slop At Work
I work at a C++ shop with coders that I really respected - very deep C++ knowledge and are building very technical deep systems products. Over the last few months the CTO has gone off the deep end with AI talking of creating software factory (He’s been reading too much X), he releases huge multi thousand line PRs with basically no review. All sense of scientific temperament and engineering rigour has gone out of the window it seems.
I do believe that AI is a transformational tool and I use it plenty in the development process but I still strive to understand what the AI has written and often use the AI as multiplier rather than surrendering my thinking to it. it’s become increasingly hard to actually develop while deeply understanding the codebase because it has become so sloppy.
I am very sad as this means I’m not really interfacing with writing C++ as much and exploring cool new corners of the language in my daily work.
There is definitely some cool stuff this lets us do a bit more of - high level planning and systems design by reading many papers as well as exploring formal verification.
But overall I am left disappointed. I wonder how it is like at everyone else’s work places and if anyone has any thoughts and suggestions on how I can still develop my C++ knowledge.
https://redd.it/1xpshkh
@r_cpp
I work at a C++ shop with coders that I really respected - very deep C++ knowledge and are building very technical deep systems products. Over the last few months the CTO has gone off the deep end with AI talking of creating software factory (He’s been reading too much X), he releases huge multi thousand line PRs with basically no review. All sense of scientific temperament and engineering rigour has gone out of the window it seems.
I do believe that AI is a transformational tool and I use it plenty in the development process but I still strive to understand what the AI has written and often use the AI as multiplier rather than surrendering my thinking to it. it’s become increasingly hard to actually develop while deeply understanding the codebase because it has become so sloppy.
I am very sad as this means I’m not really interfacing with writing C++ as much and exploring cool new corners of the language in my daily work.
There is definitely some cool stuff this lets us do a bit more of - high level planning and systems design by reading many papers as well as exploring formal verification.
But overall I am left disappointed. I wonder how it is like at everyone else’s work places and if anyone has any thoughts and suggestions on how I can still develop my C++ knowledge.
https://redd.it/1xpshkh
@r_cpp
Reddit
From the cpp community on Reddit
Explore this post and more from the cpp community
Stack vs heap for memory throughput
Hi,
I have a high datarate application (120 MB/s) which needs to work on an embedded system.
currently I use zmq to publsih the data on a socket. zmq takes a raw pointer to data, and needs to specify a deletion function when data is published. So I use malloc and free for that specific part. So this is all done on the heap.
would it be worth it to do this on the stack? The problem is, I cannot control how fast data is consumed, so I need a growing buffer of memory. In the end, data will be consumed realtime, but it may take some time before the system ”settles”. Preallocating a huge amount of memory on the stack is also not very desireable, due to memory constraints.
how do I approach performance optimization for memory management? I’ve already cut out all unneccesary copy operations.
https://redd.it/1xr3nfx
@r_cpp
Hi,
I have a high datarate application (120 MB/s) which needs to work on an embedded system.
currently I use zmq to publsih the data on a socket. zmq takes a raw pointer to data, and needs to specify a deletion function when data is published. So I use malloc and free for that specific part. So this is all done on the heap.
would it be worth it to do this on the stack? The problem is, I cannot control how fast data is consumed, so I need a growing buffer of memory. In the end, data will be consumed realtime, but it may take some time before the system ”settles”. Preallocating a huge amount of memory on the stack is also not very desireable, due to memory constraints.
how do I approach performance optimization for memory management? I’ve already cut out all unneccesary copy operations.
https://redd.it/1xr3nfx
@r_cpp
Reddit
From the cpp community on Reddit
Explore this post and more from the cpp community