From fe6effef5e48218de1ac3731a3c1459e006d372a Mon Sep 17 00:00:00 2001 From: Luke Hubmayer-Werner Date: Wed, 7 Dec 2022 17:56:48 +1030 Subject: [PATCH] Update C++ benching --- 2022/day6.cpp | 55 ++++++++++++++++++++++++++++++--------------------- 1 file changed, 33 insertions(+), 22 deletions(-) diff --git a/2022/day6.cpp b/2022/day6.cpp index b977ed3..983ac32 100644 --- a/2022/day6.cpp +++ b/2022/day6.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include #include @@ -80,36 +81,46 @@ fourteen_found: return std::pair(four+2, fourteen+8); } -void run_once(std::vector *s) { - size_t four = find_first_unique_run(s, 4, 4); - size_t fourteen = find_first_unique_run(s, 14, four); - std::cout << "Part 1: " << four << '\n'; - std::cout << "Part 2: " << fourteen << '\n'; -} +int main(int argc, char **argv) { + size_t iterations = 1000000; + auto filename = "input/6"; + switch(argc) { + case 3: // a.out filename iterations + iterations = std::stoi(argv[2]); + // std::cout << "Set iterations to: " << iterations << '\n'; // fallthrough + case 2: // a.out filename + filename = argv[1]; + // std::cout << "Set filename to: " << filename << '\n'; + default: + break; + } + + auto input_file = std::ifstream(filename, std::ios::binary | std::ios::ate); + const std::streamoff eof_position = static_cast(input_file.tellg()); + auto s = std::vector(eof_position); + input_file.seekg(0, std::ios::beg); + input_file.read(reinterpret_cast(s.data()), eof_position); -void run_many(std::vector *s, size_t iterations) { size_t volatile four = 0; // Don't you dare optimize out the iterations! size_t volatile fourteen = 0; std::cout << "Running " << iterations << " iterations:\n"; + auto clock = std::chrono::high_resolution_clock(); + auto t0 = clock.now(); for (size_t i = 0; i result = find_first_unique_runs(s); + // four = find_first_unique_run(&s, 4, 4); + // fourteen = find_first_unique_run(&s, 14, four); + auto result = find_first_unique_runs(&s); four = result.first; fourteen = result.second; } + auto t1 = clock.now(); + auto delta = t1 - t0; + auto per_iteration = delta / iterations; std::cout << "Part 1: " << four << '\n'; std::cout << "Part 2: " << fourteen << '\n'; - std::cout << "Completed " << iterations << " iterations\n"; -} - -int main() { - std::ifstream input_file("input/6", std::ios::binary | std::ios::ate); - const std::streamoff eof_position = static_cast(input_file.tellg()); - std::vector input = std::vector(eof_position); - input_file.seekg(0, std::ios::beg); - input_file.read(reinterpret_cast(input.data()), eof_position); - - // run_once(&input); - run_many(&input, 10000000); + std::cout << "Completed " << iterations << " iterations in " + << std::chrono::duration_cast(delta).count() + << "ms (~" + << std::chrono::duration_cast(per_iteration).count() + << "ns each)\n"; }