diff --git a/benchmarks/colony-performance.md b/benchmarks/colony-performance.md new file mode 100644 index 0000000..d70c221 --- /dev/null +++ b/benchmarks/colony-performance.md @@ -0,0 +1,26 @@ +# Производительность симуляции колонии + +Карта 80 × 80, seed 2026. На каждые десять жителей приходятся четыре фермера, два лесоруба, шахтёр и три строителя. Они засевают поля, высаживают деревья, добывают камень, работают на станках и строят кровати. Ткань производят жители из выращенного льна. + +Замеры выполнены на Windows, AMD Ryzen 9 9950X3D, сборка Release. Для каждой конфигурации показаны медианы трёх запусков после 32 тиков прогрева. В каждом запуске измерено 240 тиков ядра. p95 показывает время, за которое укладываются 95% тиков. Отрисовка, сохранения и сеть в эти замеры не входят. + +| Жителей | p50, 6 потоков (мкс) | p95, 6 потоков (мкс) | p50, 12 потоков (мкс) | p95, 12 потоков (мкс) | +| ---: | ---: | ---: | ---: | ---: | +| 50 | 17,5 | 97,7 | 38,7 | 123,4 | +| 100 | 21,1 | 101,2 | 38,1 | 128,6 | +| 250 | 37,4 | 164,0 | 52,5 | 184,9 | +| 500 | 81,3 | 268,7 | 96,5 | 279,7 | + +На 500 жителях кэш обслужил 9 025 из 13 051 запросов маршрута. При шести потоках выдача работ на стройке и в мастерских заняла в среднем 49,84 мкс за тик, ресурсные работы — 30,70 мкс, перемещение и завершение работ — 19,46 мкс. + +`path_searches` включает повторные запросы, `path_cache_hits` показывает число запросов, обслуженных кэшем. `logical_path_nodes` указывает число узлов, которое потребовалось бы без повторного использования маршрутов. + +## Повторный запуск + +```powershell +foreach ($residents in 50, 100, 250, 500) { + foreach ($workers in 6, 12) { + .\build\settlement_colony_benchmark.exe $residents $workers + } +} +``` diff --git a/benchmarks/colony.cpp b/benchmarks/colony.cpp new file mode 100644 index 0000000..0405608 --- /dev/null +++ b/benchmarks/colony.cpp @@ -0,0 +1,116 @@ +#include "settlement/core/world.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using namespace settlement; +using Clock = std::chrono::steady_clock; +using Microseconds = std::chrono::duration; +constexpr int warmup_ticks = 32; +constexpr int measured_ticks = 240; + +int parse_number(std::string_view argument) { + int number = 0; + const auto end = argument.data() + argument.size(); + const auto result = std::from_chars(argument.data(), end, number); + return result.ec == std::errc{} && result.ptr == end ? number : 0; +} + +void populate(World& world, int residents) { + world.start_scenario({79, 79}); + const auto send = [&](CommandKind kind, GridPosition cell, std::uint8_t value = 0, AgentId resident = 0) { + const auto result = world.apply_command({colony_host, world.next_command_sequence(colony_host), + kind, cell, value, {}, resident}); + if (result.status != CommandStatus::Accepted) throw std::runtime_error("benchmark command rejected"); + }; + constexpr Profession roles[] = { + Profession::Farmer, Profession::Farmer, Profession::Farmer, Profession::Farmer, + Profession::Woodcutter, Profession::Woodcutter, Profession::Miner, + Profession::Builder, Profession::Builder, Profession::Builder, + }; + + for (int sector = 0; sector < residents / 10; ++sector) { + const int x = 10 * (sector % 8); + const int y = 10 * (sector / 8); + const auto pantry = world.add_storage({x + 4, y + 4}, 80, StorageKind::Pantry); + world.stock_storage(pantry, ItemType::Berries, 20); + const auto materials = world.add_storage({x + 4, y + 5}, 110); + world.stock_storage(materials, ItemType::Wood, 2); + static_cast(world.add_storage({x + 7, y + 5}, 110)); + + for (int index = 0; index < 10; ++index) { + const auto id = world.spawn_agent({x + index % 5, y + 6 + index / 5}); + send(CommandKind::AssignProfession, {}, static_cast(roles[index]), id); + } + + for (int offset = 0; offset < 2; ++offset) { + send(CommandKind::PlaceBerryField, {x + offset, y + 1}); + send(CommandKind::PlaceFlaxField, {x + offset, y + 3}); + send(CommandKind::PlaceTreePlot, {x + 6 + offset, y + 2}); + send(CommandKind::PlaceLoom, {x + 3 + offset, y + 3}); + send(CommandKind::PlaceBed, {x + 6 + offset, y + 7}); + } + const GridPosition rock{x + 8, y + 4}; + world.set_blocked(rock); + send(CommandKind::PlaceMine, rock); + } +} + +} // namespace + +int main(int argc, char** argv) try { + const int residents = argc == 3 ? parse_number(argv[1]) : 0; + const int workers = argc == 3 ? parse_number(argv[2]) : 0; + if (residents < 10 || residents > 500 || residents % 10 != 0 || + workers < static_cast(min_worker_count) || workers > 32) { + std::cerr << "Usage: settlement_colony_benchmark RESIDENTS WORKERS (10..500 by 10, 2..32)\n"; + return 2; + } + World world(2026, 80, 80, static_cast(workers)); + populate(world, residents); + for (int tick = 0; tick < warmup_ticks; ++tick) world.step(); + const auto baseline_paths = world.path_searches(); + const auto baseline_nodes = world.path_nodes_visited(); + const auto baseline_hits = world.assignment_path_cache_hits(); + + TickProfile profile; + std::vector ticks; + ticks.reserve(measured_ticks); + for (int tick = 0; tick < measured_ticks; ++tick) { + const auto start = Clock::now(); + world.step(&profile); + ticks.push_back(Microseconds(Clock::now() - start).count()); + } + std::sort(ticks.begin(), ticks.end()); + std::uint64_t cloth = 0; + for (const auto& storage : world.storages()) cloth += storage.item_count(ItemType::Cloth); + const auto average = [](auto duration) { return Microseconds(duration).count() / measured_ticks; }; + std::cout << std::fixed << std::setprecision(2) + << "residents=" << residents << '\n' + << "workers=" << workers << '\n' + << "p50_us=" << ticks[measured_ticks / 2] << '\n' + << "p95_us=" << ticks[(measured_ticks * 95 + 99) / 100 - 1] << '\n' + << "growth_needs_us=" << average(profile.growth_and_needs) << '\n' + << "resource_us=" << average(profile.resource_assignment) << '\n' + << "production_us=" << average(profile.production_assignment) << '\n' + << "other_jobs_us=" << average(profile.generic_assignment) << '\n' + << "advancement_us=" << average(profile.advancement) << '\n' + << "path_searches=" << world.path_searches() - baseline_paths << '\n' + << "path_cache_hits=" << world.assignment_path_cache_hits() - baseline_hits << '\n' + << "logical_path_nodes=" << world.path_nodes_visited() - baseline_nodes << '\n' + << "assigned_beds=" << world.scenario_progress().assigned_beds << '\n' + << "cloth_in_stock=" << cloth << '\n' + << "meals_eaten=" << world.meals_eaten() << '\n'; + return 0; +} catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; +} diff --git a/benchmarks/parallel-workers.md b/benchmarks/parallel-workers.md new file mode 100644 index 0000000..a6a7df9 --- /dev/null +++ b/benchmarks/parallel-workers.md @@ -0,0 +1,15 @@ +# Parallel simulation benchmark + +The headless workload uses 2,500 residents, 10,000 jobs and a 512 × 512 map with 8% blocked cells, seed 42. These Windows Release runs measured 250 ticks starting with initial job assignment, with zero warmup ticks. + +| Worker threads | Elapsed | Average tick | p50 tick | p95 tick | A* requests | +| ---: | ---: | ---: | ---: | ---: | ---: | +| 8 | 3.75 s | 15.00 ms | 2.13 ms | 5.49 ms | 5,013 | +| 12 | 2.92 s | 11.67 ms | 1.66 ms | 4.25 ms | 5,013 | + +```powershell +.\build\settlement_sim.exe --seed 42 --agents 2500 --jobs 10000 --map-size 512 --blocked-percent 8 --warmup 0 --ticks 250 --workers 8 +.\build\settlement_sim.exe --seed 42 --agents 2500 --jobs 10000 --map-size 512 --blocked-percent 8 --warmup 0 --ticks 250 --workers 12 +``` + +The CLI supports 2–32 workers. For fields, storage and workshops, see [the colony benchmark](colony-performance.md). diff --git a/benchmarks/scale-50-vs-2500.md b/benchmarks/scale-50-vs-2500.md new file mode 100644 index 0000000..4090d9c --- /dev/null +++ b/benchmarks/scale-50-vs-2500.md @@ -0,0 +1,13 @@ +# Scaling check: 50 vs 2,500 residents + +Both Windows Release runs used eight worker threads, seed 42, a 512 × 512 map with 8% blocked cells and 10,000 work jobs. The 250 measured ticks include initial assignment and routing. + +| Residents | Completed jobs | Active at end | A* requests | A* nodes visited | Total time | Average tick | p95 tick | +| ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| 50 | 159 | 47 | 206 | 6,185 | 69.62 ms | 0.28 ms | 0.64 ms | +| 2,500 | 2,520 | 2,493 | 5,013 | 1,662,566 | 3.75 s | 15.00 ms | 5.49 ms | + +```powershell +.\build\settlement_sim.exe --seed 42 --agents 50 --jobs 10000 --map-size 512 --blocked-percent 8 --warmup 0 --ticks 250 --workers 8 +.\build\settlement_sim.exe --seed 42 --agents 2500 --jobs 10000 --map-size 512 --blocked-percent 8 --warmup 0 --ticks 250 --workers 8 +```