Added getCPUTicks() and getCPUTicksPerSeconds() functions.

This commit is contained in:
Patrick 2025-07-12 16:59:35 +02:00
parent cf45aaa39a
commit 2d5a7316f1
2 changed files with 37 additions and 1 deletions

View File

@ -10,6 +10,7 @@
#include <mutex> #include <mutex>
#include <dlfcn.h> #include <dlfcn.h>
#include <pthread.h> #include <pthread.h>
#include <time.h>
#elif MIJIN_TARGET_OS == MIJIN_OS_WINDOWS #elif MIJIN_TARGET_OS == MIJIN_OS_WINDOWS
#include <array> #include <array>
#include <malloc.h> #include <malloc.h>
@ -42,7 +43,16 @@ namespace mijin
namespace namespace
{ {
std::mutex gDlErrorMutex; // dlerror may not be thread-safe std::mutex gDlErrorMutex; // dlerror may not be thread-safe
}
const std::uint64_t gCPUClockResolution = []()
{
struct timespec time;
[[maybe_unused]] const int result = clock_getres(CLOCK_PROCESS_CPUTIME_ID, &time);
MIJIN_ASSERT(result == 0, "Error getting cputime resolution.");
MIJIN_ASSERT(time.tv_sec == 0, "What kind of cpu clock is this?");
return static_cast<std::uint64_t>(time.tv_nsec);
}();
};
#endif // MIJIN_TARGET_OS == MIJIN_OS_LINUX #endif // MIJIN_TARGET_OS == MIJIN_OS_LINUX
// //
@ -178,4 +188,26 @@ void alignedFree(void* ptr)
#endif #endif
} }
std::uint64_t getCPUTicks() MIJIN_NOEXCEPT
{
#if MIJIN_TARGET_OS == MIJIN_OS_LINUX
struct timespec time;
[[maybe_unused]] const int result = clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time);
MIJIN_ASSERT(result == 0, "Error getting cpu time.");
return (static_cast<std::uint64_t>(time.tv_sec) * 1e9 + time.tv_nsec) / gCPUClockResolution;
#else
MIJIN_ERROR("TODO");
return 0;
#endif
}
std::uint64_t getCPUTicksPerSecond() MIJIN_NOEXCEPT
{
#if MIJIN_TARGET_OS == MIJIN_OS_LINUX
return 1e9 / gCPUClockResolution;
#else
MIJIN_ERROR("TODO");
return 0;
#endif
}
} // namespace mijin } // namespace mijin

View File

@ -5,6 +5,7 @@
#define MIJIN_UTIL_OS_HPP_INCLUDED 1 #define MIJIN_UTIL_OS_HPP_INCLUDED 1
#include <csignal> #include <csignal>
#include <cstdint>
#include <string> #include <string>
#include <string_view> #include <string_view>
#include <utility> #include <utility>
@ -85,6 +86,9 @@ void setCurrentThreadName(const char* threadName) MIJIN_NOEXCEPT;
[[nodiscard]] void* alignedRealloc(void* ptr, std::size_t alignment, std::size_t size) MIJIN_NOEXCEPT; [[nodiscard]] void* alignedRealloc(void* ptr, std::size_t alignment, std::size_t size) MIJIN_NOEXCEPT;
void alignedFree(void* ptr); void alignedFree(void* ptr);
[[nodiscard]] std::uint64_t getCPUTicks() MIJIN_NOEXCEPT;
[[nodiscard]] std::uint64_t getCPUTicksPerSecond() MIJIN_NOEXCEPT;
SharedLibrary::~SharedLibrary() MIJIN_NOEXCEPT SharedLibrary::~SharedLibrary() MIJIN_NOEXCEPT
{ {
close(); close();