Implement getting CPU usage in linux.

This commit is contained in:
Bartosz Taudul 2019-02-24 19:02:49 +01:00
parent 0c75a5178c
commit bafc8a1330
2 changed files with 41 additions and 24 deletions

View File

@ -4,6 +4,10 @@
# if defined _WIN32 || defined __CYGWIN__
# include <windows.h>
# elif defined __linux__
# include <assert.h>
# include <stdio.h>
# include <inttypes.h>
# endif
namespace tracy
@ -16,7 +20,7 @@ static inline uint64_t ConvertTime( const FILETIME& t )
return ( uint64_t( t.dwHighDateTime ) << 32 ) | uint64_t( t.dwLowDateTime );
}
SysTime::SysTime()
void SysTime::ReadTimes()
{
FILETIME idleTime;
FILETIME kernelTime;
@ -30,29 +34,42 @@ SysTime::SysTime()
used = kernel + user;
}
float SysTime::Get()
# elif defined __linux__
void SysTime::ReadTimes()
{
FILETIME idleTime;
FILETIME kernelTime;
FILETIME userTime;
GetSystemTimes( &idleTime, &kernelTime, &userTime );
const auto newIdle = ConvertTime( idleTime );
const auto kernel = ConvertTime( kernelTime );
const auto user = ConvertTime( userTime );
const auto newUsed = kernel + user;
const auto diffIdle = newIdle - idle;
const auto diffUsed = newUsed - used;
idle = newIdle;
used = newUsed;
return diffUsed == 0 ? 0 : ( diffUsed - diffIdle ) * 100.f / diffUsed;
uint64_t user, nice, system;
FILE* f = fopen( "/proc/stat", "r" );
assert( f );
fscanf( f, "cpu %" PRIu64 " %" PRIu64 " %" PRIu64" %" PRIu64, &user, &nice, &system, &idle );
fclose( f );
used = user + nice + system;
}
# endif
#endif
SysTime::SysTime()
{
ReadTimes();
}
float SysTime::Get()
{
const auto oldUsed = used;
const auto oldIdle = idle;
ReadTimes();
const auto diffIdle = idle - oldIdle;
const auto diffUsed = used - oldUsed;
#if defined _WIN32 || defined __CYGWIN__
return diffUsed == 0 ? 0 : ( diffUsed - diffIdle ) * 100.f / diffUsed;
#elif defined __linux__
const auto total = diffUsed + diffIdle;
return total == 0 ? 0 : diffUsed * 100.f / total;
#endif
}
}

View File

@ -1,7 +1,7 @@
#ifndef __TRACYSYSTIME_HPP__
#define __TRACYSYSTIME_HPP__
#if defined _WIN32 || defined __CYGWIN__
#if defined _WIN32 || defined __CYGWIN__ || defined __linux__
# define TRACY_HAS_SYSTIME
#endif
@ -18,10 +18,10 @@ public:
SysTime();
float Get();
void ReadTimes();
private:
# if defined _WIN32 || defined __CYGWIN__
uint64_t idle, used;
# endif
};
}