From e61bc1d55ae7853ff99ac082e0a10cf7d82005c1 Mon Sep 17 00:00:00 2001 From: j2-mcdaid <jack2.mcdaid@live.uwe.ac.uk> Date: Fri, 6 Dec 2024 17:56:54 +0000 Subject: [PATCH] Upload New File --- Worksheets/Worksheet2/Task 3/bench.hpp | 52 ++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Worksheets/Worksheet2/Task 3/bench.hpp diff --git a/Worksheets/Worksheet2/Task 3/bench.hpp b/Worksheets/Worksheet2/Task 3/bench.hpp new file mode 100644 index 0000000..cfa6b86 --- /dev/null +++ b/Worksheets/Worksheet2/Task 3/bench.hpp @@ -0,0 +1,52 @@ + +#ifndef BENCH_HPP +#define BENCH_HPP + +#include <chrono> +#include <iostream> +#include <numeric> +#include <vector> +#include <algorithm> +#include <string> +#include <functional> + + +class bench{ +private: + // calculate and print usefull benchmark results + static void Results(const std::string& testName, const std::vector<double>& durations){ + double sum = std::accumulate(durations.begin(), durations.end(), 0.0); + double mean = sum/durations.size(); + + std::vector<double> sortedDurations = durations; + std::sort(sortedDurations.begin(), sortedDurations.end()); + double median = sortedDurations[sortedDurations.size() / 2]; + + std::cout << "Benchmark: " << testName << std::endl; + std::cout << "Mean: " << mean << std::endl; + std::cout << "Median: " << median << std::endl; + std::cout << "Runs: " << durations.size() << std::endl; + std::cout << "------------------------------" << std::endl; + } + +public: + // template function for benchmark tests taking arguments so usefull for multiple tests + template <typename Func, typename... Args> + static void Run(const std::string& testName, Func func, Args... args){ + using Clock = std::chrono::system_clock; + std::vector<double> durations; + + // basic iterative for loop + for (int i = 0; i < 10; ++i){ + auto start = Clock::now(); + func(args...); + auto end = Clock::now(); + std::chrono::duration<double, std::milli> duration = end-start; + durations.push_back(duration.count()); + } + Results(testName, durations); + } +}; + + +#endif \ No newline at end of file -- GitLab