main.cppcpp · 48 linesall
// Cost of locating the visible range for variable-height rows:
// a per-frame linear walk (egui_extras heterogeneous_rows) versus retained prefix sums
// (VS Code RangeMap / egui #1376's "store the bounds ... binary search") and a Fenwick tree
// for O(log N) height updates. Probe for immediate-mode-large-views.md.
#include <algorithm>
#include <chrono>
#include <cstdio>
#include <random>
#include <vector>
using clk = std::chrono::steady_clock;
static double us(clk::time_point a, clk::time_point b) { return std::chrono::duration<double, std::micro>(b - a).count(); }
int main() {
    for (int n : {1000, 10000, 100000, 1000000}) {
        std::mt19937 rng(42);
        std::vector<float> h(n);
        for (auto& x : h) x = 18.0f + 18.0f * (rng() % 4); // 1-4 lines
        const int reps = 200;
        volatile double sink = 0;
        // per-frame linear walk to the scroll offset at 50% of the content (what heterogeneous_rows does)
        double total = 0; for (float x : h) total += x;
        auto a = clk::now();
        for (int r = 0; r < reps; r++) {
            double y = 0, target = total * 0.5 + r; int i = 0;
            for (; i < n && y + h[i] < target; i++) y += h[i];
            double rest = 0; for (int j = i; j < n; j++) rest += h[j]; // the walk also sums the tail for the extent
            sink = sink + i + rest;
        }
        auto b = clk::now();
        // retained prefix sums: build once, binary-search per frame
        std::vector<double> pre(n + 1, 0.0);
        auto c = clk::now();
        for (int i = 0; i < n; i++) pre[i + 1] = pre[i] + h[i];
        auto d = clk::now();
        for (int r = 0; r < reps * 1000; r++) {
            double target = pre[n] * 0.5 + r % 1000;
            sink = sink + (std::upper_bound(pre.begin(), pre.end(), target) - pre.begin());
        }
        auto e = clk::now();
        // Fenwick: update one row's height (a wrapped row re-measured) in O(log N)
        std::vector<double> fw(n + 1, 0.0);
        for (int i = 1; i <= n; i++) { fw[i] += h[i - 1]; int p = i + (i & -i); if (p <= n) fw[p] += fw[i]; }
        auto f = clk::now();
        for (int r = 0; r < reps * 1000; r++) { int i = (r * 7919) % n + 1; for (; i <= n; i += i & -i) fw[i] += 1.0; }
        auto g = clk::now();
        printf("N=%d\twalk_per_frame_us=%.1f\tprefix_build_us=%.0f\tbsearch_ns=%.1f\tfenwick_update_ns=%.1f\n",
               n, us(a, b) / reps, us(c, d), us(d, e) * 1000 / (reps * 1000), us(f, g) * 1000 / (reps * 1000));
    }
}