From 42b8c8d7e75af9f5a442cbd8f8a8486c8dbf5384 Mon Sep 17 00:00:00 2001 From: Michael Mandl Date: Wed, 20 Mar 2024 10:13:08 +0100 Subject: [PATCH] feat: implement ostream operator for timer --- lib_vector_search/include/timer.h | 2 ++ lib_vector_search/src/timer.cpp | 18 ++++++++++++++++++ vector_search_cli/main.cpp | 6 +++--- 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/lib_vector_search/include/timer.h b/lib_vector_search/include/timer.h index c04724f..e7fc1d6 100644 --- a/lib_vector_search/include/timer.h +++ b/lib_vector_search/include/timer.h @@ -15,3 +15,5 @@ public: long us() const; }; + +std::ostream &operator<<(std::ostream &os, const Timer &timer); diff --git a/lib_vector_search/src/timer.cpp b/lib_vector_search/src/timer.cpp index 960868c..a663e3e 100644 --- a/lib_vector_search/src/timer.cpp +++ b/lib_vector_search/src/timer.cpp @@ -12,3 +12,21 @@ long Timer::us() const { return std::chrono::duration_cast(end_ - start_) .count(); } + +std::ostream &operator<<(std::ostream &os, const Timer &timer) { + long time = timer.us(); + + if (time >= 1e6) { + os << time / static_cast(1e6) << " s "; + time %= static_cast(1e6); + } + + if (time >= 1e3) { + os << time / static_cast(1e3) << " ms "; + time %= static_cast(1e3); + } + + os << time << " µs"; + + return os; +} diff --git a/vector_search_cli/main.cpp b/vector_search_cli/main.cpp index f0377f9..ace12f7 100644 --- a/vector_search_cli/main.cpp +++ b/vector_search_cli/main.cpp @@ -17,7 +17,7 @@ vector generate_word_list() { auto word_list = WordListGenerator().generate(); generator_timer.stop(); - cout << "word list generator took " << generator_timer.us() << " µs" << endl; + cout << "word list generator took " << generator_timer << endl; cout << "word list is " << word_list.size() << " element(s) long" << endl; return word_list; @@ -34,7 +34,7 @@ void test_linear_finder(const vector &word_list) { auto result = linear_finder.find_prefix("ABCD"); find_timer.stop(); - cout << "linear finder took " << find_timer.us() << " µs" << endl; + cout << "linear finder took " << find_timer << endl; cout << "result list is " << result.size() << " element(s) long" << endl; } @@ -53,7 +53,7 @@ void test_parallel_finder(const vector &word_list) { auto result = parallel_finder.find_prefix("ABCD"); find_timer.stop(); - cout << "parallel finder took " << find_timer.us() << " µs" << endl; + cout << "parallel finder took " << find_timer << endl; cout << "result list is " << result.size() << " element(s) long" << endl; }