Skip to content

Commit

Permalink
Set the minimum resolution for Windows clock
Browse files Browse the repository at this point in the history
  • Loading branch information
GiulioRomualdi committed Oct 30, 2024
1 parent a60b73d commit 825b51e
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/System/include/BipedalLocomotion/System/StdClock.h
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,33 @@ class StdClock final : public IClock
* threads to run.
*/
void yield() final;

private:

/**
* PrecisionScheduler is a class that allows to set the system timer resolution to the minimum
* value for higher precision. This class is used only on Windows systems.
*/
struct PrecisionScheduler
{
/**
* Constructor.
* It sets the system timer resolution to the minimum value for higher precision.
* @note Only affects Windows systems.
*/
PrecisionScheduler();

/**
* Destructor.
* It restores the system timer resolution to the default value.
* @note Only affects Windows systems.
*/
~PrecisionScheduler();
};

PrecisionScheduler m_precisionScheduler; /**< PrecisionScheduler object.
It is used only on Windows systems. */

};

class StdClockFactory final : public ClockFactory
Expand Down
28 changes: 28 additions & 0 deletions src/System/src/StdClock.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@
#include <chrono>
#include <thread>

#if defined(_WIN32)
#include <Windows.h>
#endif

#include <BipedalLocomotion/System/StdClock.h>

using namespace BipedalLocomotion::System;
Expand All @@ -32,6 +36,30 @@ void StdClock::yield()
std::this_thread::yield();
}

StdClock::PrecisionScheduler::PrecisionScheduler()
{
#if defined(_WIN32)
// Only affects Windows systems.
TIMECAPS tm; // Stores system timer capabilities.
// Get the minimum timer resolution supported by the system.
timeGetDevCaps(&tm, sizeof(TIMECAPS));
// Set the system timer resolution to the minimum value for higher precision.
timeBeginPeriod(tm.wPeriodMin);
#endif
}

StdClock::PrecisionScheduler::~PrecisionScheduler()
{
#if defined(_WIN32)
// Only affects Windows systems.
TIMECAPS tm; // Stores system timer capabilities.
// Get the minimum timer resolution supported by the system.
timeGetDevCaps(&tm, sizeof(TIMECAPS));
// Restore the system timer resolution to the default value.
timeEndPeriod(tm.wPeriodMin);
#endif
}

IClock& StdClockFactory::createClock()
{
// Create the singleton. Meyers' implementation. It is automatically threadsafe
Expand Down

0 comments on commit 825b51e

Please sign in to comment.