fsfw/timemanager/Stopwatch.cpp

75 lines
2.1 KiB
C++
Raw Normal View History

2020-09-18 13:03:48 +02:00
#include "Stopwatch.h"
2021-01-22 12:21:45 +01:00
#include "../serviceinterface/ServiceInterface.h"
2021-01-27 18:03:56 +01:00
#if FSFW_CPP_OSTREAM_ENABLED == 1
2020-08-13 20:53:35 +02:00
#include <iomanip>
2021-01-27 18:03:56 +01:00
#endif
2020-08-13 20:53:35 +02:00
Stopwatch::Stopwatch(bool displayOnDestruction,
StopwatchDisplayMode displayMode): displayOnDestruction(
displayOnDestruction), displayMode(displayMode) {
// Measures start time on initialization.
2020-09-18 12:27:40 +02:00
Clock::getUptime(&startTime);
2020-08-13 20:53:35 +02:00
}
void Stopwatch::start() {
2020-09-18 12:27:40 +02:00
Clock::getUptime(&startTime);
2020-08-13 20:53:35 +02:00
}
2020-09-18 12:27:40 +02:00
dur_millis_t Stopwatch::stop(bool display) {
2020-08-13 20:53:35 +02:00
stopInternal();
2020-09-18 12:27:40 +02:00
if(display) {
this->display();
}
2020-08-13 20:53:35 +02:00
return elapsedTime.tv_sec * 1000 + elapsedTime.tv_usec / 1000;
}
2020-09-18 12:27:40 +02:00
double Stopwatch::stopSeconds() {
2020-08-13 20:53:35 +02:00
stopInternal();
return timevalOperations::toDouble(elapsedTime);
}
void Stopwatch::display() {
if(displayMode == StopwatchDisplayMode::MILLIS) {
2021-01-22 12:21:45 +01:00
dur_millis_t timeMillis = static_cast<dur_millis_t>(
elapsedTime.tv_sec * 1000 + elapsedTime.tv_usec / 1000);
2021-01-03 14:16:52 +01:00
#if FSFW_CPP_OSTREAM_ENABLED == 1
2021-01-22 12:21:45 +01:00
sif::info << "Stopwatch: Operation took " << timeMillis << " milliseconds" << std::endl;
#else
sif::printInfo("Stopwatch: Operation took %lu milliseconds\n\r",
static_cast<unsigned int>(timeMillis));
#endif
2020-08-13 20:53:35 +02:00
}
else if(displayMode == StopwatchDisplayMode::SECONDS) {
2021-01-03 14:16:52 +01:00
#if FSFW_CPP_OSTREAM_ENABLED == 1
2020-08-13 20:53:35 +02:00
sif::info <<"Stopwatch: Operation took " << std::setprecision(3)
<< std::fixed << timevalOperations::toDouble(elapsedTime)
<< " seconds" << std::endl;
2021-01-22 12:21:45 +01:00
#else
sif::printInfo("Stopwatch: Operation took %.3f seconds\n\r",
static_cast<float>(timevalOperations::toDouble(elapsedTime)));
#endif
2020-08-13 20:53:35 +02:00
}
}
Stopwatch::~Stopwatch() {
if(displayOnDestruction) {
stopInternal();
display();
}
}
void Stopwatch::setDisplayMode(StopwatchDisplayMode displayMode) {
this->displayMode = displayMode;
}
StopwatchDisplayMode Stopwatch::getDisplayMode() const {
return displayMode;
}
void Stopwatch::stopInternal() {
timeval endTime;
2020-09-18 12:27:40 +02:00
Clock::getUptime(&endTime);
2020-08-13 20:53:35 +02:00
elapsedTime = endTime - startTime;
}