feat: implement ostream operator for timer

main
mandlm 2024-03-20 10:13:08 +01:00
parent 64ae4c62a9
commit 42b8c8d7e7
Signed by: mandlm
GPG Key ID: 4AA25D647AA54CC7
3 changed files with 23 additions and 3 deletions

View File

@ -15,3 +15,5 @@ public:
long us() const; long us() const;
}; };
std::ostream &operator<<(std::ostream &os, const Timer &timer);

View File

@ -12,3 +12,21 @@ long Timer::us() const {
return std::chrono::duration_cast<std::chrono::microseconds>(end_ - start_) return std::chrono::duration_cast<std::chrono::microseconds>(end_ - start_)
.count(); .count();
} }
std::ostream &operator<<(std::ostream &os, const Timer &timer) {
long time = timer.us();
if (time >= 1e6) {
os << time / static_cast<long>(1e6) << " s ";
time %= static_cast<long>(1e6);
}
if (time >= 1e3) {
os << time / static_cast<long>(1e3) << " ms ";
time %= static_cast<long>(1e3);
}
os << time << " µs";
return os;
}

View File

@ -17,7 +17,7 @@ vector<string> generate_word_list() {
auto word_list = WordListGenerator().generate(); auto word_list = WordListGenerator().generate();
generator_timer.stop(); 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; cout << "word list is " << word_list.size() << " element(s) long" << endl;
return word_list; return word_list;
@ -34,7 +34,7 @@ void test_linear_finder(const vector<string> &word_list) {
auto result = linear_finder.find_prefix("ABCD"); auto result = linear_finder.find_prefix("ABCD");
find_timer.stop(); 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; cout << "result list is " << result.size() << " element(s) long" << endl;
} }
@ -53,7 +53,7 @@ void test_parallel_finder(const vector<string> &word_list) {
auto result = parallel_finder.find_prefix("ABCD"); auto result = parallel_finder.find_prefix("ABCD");
find_timer.stop(); 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; cout << "result list is " << result.size() << " element(s) long" << endl;
} }