TracySysTime.cpp (2399B)
1 #include "TracySysTime.hpp" 2 3 #ifdef TRACY_HAS_SYSTIME 4 5 # if defined _WIN32 || defined __CYGWIN__ 6 # include <windows.h> 7 # elif defined __linux__ 8 # include <stdio.h> 9 # include <inttypes.h> 10 # elif defined __APPLE__ 11 # include <mach/mach_host.h> 12 # include <mach/host_info.h> 13 # elif defined BSD 14 # include <sys/types.h> 15 # include <sys/sysctl.h> 16 # endif 17 18 namespace tracy 19 { 20 21 # if defined _WIN32 || defined __CYGWIN__ 22 23 static inline uint64_t ConvertTime( const FILETIME& t ) 24 { 25 return ( uint64_t( t.dwHighDateTime ) << 32 ) | uint64_t( t.dwLowDateTime ); 26 } 27 28 void SysTime::ReadTimes() 29 { 30 FILETIME idleTime; 31 FILETIME kernelTime; 32 FILETIME userTime; 33 34 GetSystemTimes( &idleTime, &kernelTime, &userTime ); 35 36 idle = ConvertTime( idleTime ); 37 const auto kernel = ConvertTime( kernelTime ); 38 const auto user = ConvertTime( userTime ); 39 used = kernel + user; 40 } 41 42 # elif defined __linux__ 43 44 void SysTime::ReadTimes() 45 { 46 uint64_t user, nice, system; 47 FILE* f = fopen( "/proc/stat", "r" ); 48 if( f ) 49 { 50 fscanf( f, "cpu %" PRIu64 " %" PRIu64 " %" PRIu64" %" PRIu64, &user, &nice, &system, &idle ); 51 fclose( f ); 52 used = user + nice + system; 53 } 54 } 55 56 # elif defined __APPLE__ 57 58 void SysTime::ReadTimes() 59 { 60 host_cpu_load_info_data_t info; 61 mach_msg_type_number_t cnt = HOST_CPU_LOAD_INFO_COUNT; 62 host_statistics( mach_host_self(), HOST_CPU_LOAD_INFO, reinterpret_cast<host_info_t>( &info ), &cnt ); 63 used = info.cpu_ticks[CPU_STATE_USER] + info.cpu_ticks[CPU_STATE_NICE] + info.cpu_ticks[CPU_STATE_SYSTEM]; 64 idle = info.cpu_ticks[CPU_STATE_IDLE]; 65 } 66 67 # elif defined BSD 68 69 void SysTime::ReadTimes() 70 { 71 u_long data[5]; 72 size_t sz = sizeof( data ); 73 sysctlbyname( "kern.cp_time", &data, &sz, nullptr, 0 ); 74 used = data[0] + data[1] + data[2] + data[3]; 75 idle = data[4]; 76 } 77 78 #endif 79 80 SysTime::SysTime() 81 { 82 ReadTimes(); 83 } 84 85 float SysTime::Get() 86 { 87 const auto oldUsed = used; 88 const auto oldIdle = idle; 89 90 ReadTimes(); 91 92 const auto diffIdle = idle - oldIdle; 93 const auto diffUsed = used - oldUsed; 94 95 #if defined _WIN32 || defined __CYGWIN__ 96 return diffUsed == 0 ? -1 : ( diffUsed - diffIdle ) * 100.f / diffUsed; 97 #elif defined __linux__ || defined __APPLE__ || defined BSD 98 const auto total = diffUsed + diffIdle; 99 return total == 0 ? -1 : diffUsed * 100.f / total; 100 #endif 101 } 102 103 } 104 105 #endif