int SystemInformation::GetCpuUsage(){ FILETIME idle, prev_idle; FILETIME kernel, prev_kernel; FILETIME user, prev_user; GetSystemTimes(&prev_idle, &prev_kernel, &prev_user); Sleep(1000); GetSystemTimes(&idle, &kernel, &user); ULONGLONG sys = (ft2ull(user) - ft2ull(prev_user)) + (ft2ull(kernel) - ft2ull(prev_kernel)); int cpu = int((sys - ft2ull(idle) + ft2ull(prev_idle)) * 100.0 / sys); prev_idle = idle; prev_kernel = kernel; prev_user = user; return cpu; }
// Get CPU usage and return as a value from 0 to 255 static byte getCPUUsage() { static unsigned long long last_idleTime; static unsigned long long last_kernelTime; static unsigned long long last_userTime; unsigned long long idleTime; unsigned long long kernelTime; unsigned long long userTime; bool res = GetSystemTimes((LPFILETIME)&idleTime, (LPFILETIME)&kernelTime, (LPFILETIME)&userTime); UNREFERENCED_PARAMETER(res); unsigned long long idl = idleTime - last_idleTime; unsigned long long ker = kernelTime - last_kernelTime; unsigned long long usr = userTime - last_userTime; unsigned long long sys = ker + usr; last_idleTime = idleTime; last_kernelTime = kernelTime; last_userTime = userTime; if(sys == 0) return 0; return (byte)((sys - idl) * 255 / sys); }
/// <summary> /// Returns the average CPU usage of the current process in the range [0, 1]. /// Also returns the average total CPU usage if `totalUsage` is non-NULL. /// </summary> float WinCPUUsage::getAvgUsage(float *totalUsage) { // Fetch current CPU statistics FILETIME curSysIdle, curSysKernel, curSysUser, curProcKernel, curProcUser; FILETIME createTime, exitTime; GetSystemTimes(&curSysIdle, &curSysKernel, &curSysUser); GetProcessTimes(GetCurrentProcess(), &createTime, &exitTime, &curProcKernel, &curProcUser); // Calculate the change over time quint64 diffSysIdle = fileTimeToUInt64(curSysIdle) - fileTimeToUInt64(m_startSysIdle); quint64 diffSysKernel = fileTimeToUInt64(curSysKernel) - fileTimeToUInt64(m_startSysKernel); quint64 diffSysUser = fileTimeToUInt64(curSysUser) - fileTimeToUInt64(m_startSysUser); quint64 diffProcKernel = fileTimeToUInt64(curProcKernel) - fileTimeToUInt64(m_startProcKernel); quint64 diffProcUser = fileTimeToUInt64(curProcUser) - fileTimeToUInt64(m_startProcUser); // Calculate the average total CPU usage if the caller requested it if(totalUsage != NULL) { quint64 totalTime = diffSysKernel + diffSysUser; quint64 totalIdleTime = diffSysIdle; *totalUsage = 1.0f - (float)((double)totalIdleTime / (double)totalTime); } // Calculate and return the ratio of processor time vs total time. Note // that the system kernel time includes idle time quint64 totalTime = diffSysKernel + diffSysUser; quint64 totalProcTime = diffProcKernel + diffProcUser; return (float)((double)totalProcTime / (double)totalTime); }
static int stat_gettext(int tag, char *buf) { char *original_buf = buf; /* TODO: Support more than one processors */ LARGE_INTEGER idle_time, kernel_time, user_time; GetSystemTimes((FILETIME *)&idle_time, (FILETIME *)&kernel_time, (FILETIME *)&user_time); uint64_t user = user_time.QuadPart / (TICKS_PER_SECOND / USER_HZ); uint64_t nice = 0; uint64_t system = kernel_time.QuadPart / (TICKS_PER_SECOND / USER_HZ); uint64_t idle = idle_time.QuadPart / (TICKS_PER_SECOND / USER_HZ); system -= idle; /* KernelTime includes IdleTime */ uint64_t iowait = 0; uint64_t irq = 0; uint64_t softirq = 0; uint64_t steal = 0, guest = 0, guest_nice = 0; buf += ksprintf(buf, "cpu %llu %llu %llu %llu %llu %llu %llu %llu %llu %llu\n", user, nice, system, idle, iowait, irq, softirq, steal, guest, guest_nice); buf += ksprintf(buf, "intr %llu\n", 0); buf += ksprintf(buf, "swap %llu %llu\n", 0); uint64_t ctxt = 0; buf += ksprintf(buf, "ctxt %llu\n", ctxt); /* Boot time */ SYSTEM_TIMEOFDAY_INFORMATION tod_info; NtQuerySystemInformation(SystemTimeOfDayInformation, &tod_info, sizeof(tod_info), NULL); uint64_t btime = filetime_to_unix_sec((FILETIME *)&tod_info.BootTime); buf += ksprintf(buf, "btime %llu\n", btime); uint64_t processes = 0; buf += ksprintf(buf, "processes %llu\n", processes); int procs_running = 1; buf += ksprintf(buf, "procs_running %d\n", procs_running); int procs_blocked = 0; buf += ksprintf(buf, "procs_blocked %d\n", procs_blocked); return buf - original_buf; }
int CPUEngine_win::getSystemTimes() { FILETIME idleTime; FILETIME kernelTime; FILETIME userTime; if (!GetSystemTimes(&idleTime, &kernelTime, &userTime)) return 0; if (m_sppi_cb != sizeof(LH_SPPI)) { m_sppi_ptr = realloc(m_sppi_ptr, sizeof(LH_SPPI)); m_sppi_cb = m_sppi_ptr ? sizeof(LH_SPPI) : 0; } if (LH_SPPI *p_sppi = (LH_SPPI*) m_sppi_ptr) { memset(m_sppi_ptr, 0, m_sppi_cb); p_sppi->IdleTime.HighPart = idleTime.dwHighDateTime; p_sppi->IdleTime.LowPart = idleTime.dwLowDateTime; p_sppi->KernelTime.HighPart = kernelTime.dwHighDateTime; p_sppi->KernelTime.LowPart = kernelTime.dwLowDateTime; p_sppi->UserTime.HighPart = userTime.dwHighDateTime; p_sppi->UserTime.LowPart = userTime.dwLowDateTime; return 1; } return 0; }
void updata_temperature(void){ /******get cpu performance*******begin***/{ BOOL res ; static FILETIME preidleTime; static FILETIME prekernelTime; static FILETIME preuserTime; FILETIME idleTime; FILETIME kernelTime; FILETIME userTime; res = GetSystemTimes( &idleTime, &kernelTime, &userTime ); { __int64 idle = CompareFileTimeXXX(preidleTime,idleTime); __int64 kernel = CompareFileTimeXXX( prekernelTime, kernelTime); __int64 user = CompareFileTimeXXX(preuserTime, userTime); if((kernel+user)>0){ __int64 cpu = (kernel +user - idle) *100/(kernel+user); temperature = cpu; disp_temperature(temperature); } } /******get cpu performance*******end*****/} }
double GetCpuUseage::CpuUseage() { FILETIME idleTime; FILETIME kernelTime; FILETIME userTime; GetSystemTimes(&idleTime, &kernelTime, &userTime); int idle = CompareFileTime(m_preidleTime, idleTime); int kernel = CompareFileTime(m_prekernelTime, kernelTime); int user = CompareFileTime(m_preuserTime, userTime); if (kernel + user == 0) { return 0.0; } //(总的时间-空闲时间)/总的时间=占用cpu的时间就是使用率 double cpu = (kernel + user - idle) * 100 / (kernel + user); m_preidleTime = idleTime; m_prekernelTime = kernelTime; m_preuserTime = userTime; return cpu; }
gint32 mono_cpu_usage (MonoCpuUsageState *prev) { gint32 cpu_usage = 0; gint64 cpu_total_time; gint64 cpu_busy_time; #ifndef HOST_WIN32 struct rusage resource_usage; gint64 current_time; gint64 kernel_time; gint64 user_time; if (getrusage (RUSAGE_SELF, &resource_usage) == -1) { g_error ("getrusage() failed, errno is %d (%s)\n", errno, strerror (errno)); return -1; } current_time = mono_100ns_ticks (); kernel_time = resource_usage.ru_stime.tv_sec * 1000 * 1000 * 10 + resource_usage.ru_stime.tv_usec * 10; user_time = resource_usage.ru_utime.tv_sec * 1000 * 1000 * 10 + resource_usage.ru_utime.tv_usec * 10; cpu_busy_time = (user_time - (prev ? prev->user_time : 0)) + (kernel_time - (prev ? prev->kernel_time : 0)); cpu_total_time = (current_time - (prev ? prev->current_time : 0)) * mono_cpu_count (); if (prev) { prev->kernel_time = kernel_time; prev->user_time = user_time; prev->current_time = current_time; } #else guint64 idle_time; guint64 kernel_time; guint64 user_time; if (!GetSystemTimes ((FILETIME*) &idle_time, (FILETIME*) &kernel_time, (FILETIME*) &user_time)) { g_error ("GetSystemTimes() failed, error code is %d\n", GetLastError ()); return -1; } cpu_total_time = (gint64)((user_time - (prev ? prev->user_time : 0)) + (kernel_time - (prev ? prev->kernel_time : 0))); cpu_busy_time = (gint64)(cpu_total_time - (idle_time - (prev ? prev->idle_time : 0))); if (prev) { prev->idle_time = idle_time; prev->kernel_time = kernel_time; prev->user_time = user_time; } #endif if (cpu_total_time > 0 && cpu_busy_time > 0) cpu_usage = (gint32)(cpu_busy_time * 100 / cpu_total_time); g_assert (cpu_usage >= 0); g_assert (cpu_usage <= 100); return cpu_usage; }
virtual unsigned long long get_current_system_time_() const { FILETIME ft_idle_time, ft_kernel_time, ft_user_time; GetSystemTimes(&ft_idle_time, &ft_kernel_time, &ft_user_time); unsigned long long kernel_time = convert_filetime_to_ulonglong_( ft_kernel_time); unsigned long long user_time = convert_filetime_to_ulonglong_( ft_user_time); return kernel_time + user_time; }
ULONGLONG CpuUsage::getSystemNonIdleTimes() { FILETIME ftSysIdle, ftSysKernel, ftSysUser; if (!GetSystemTimes(&ftSysIdle, &ftSysKernel, &ftSysUser)) { errorMsg(TEXT("GetSystemTimes")); return 0; } return addTimes(ftSysKernel, ftSysUser); }
void CpuMuninNodePlugin::CalculateCpuLoad() { if (NtQuerySystemInformation != NULL && GetSystemTimes != NULL) { LONG status; SYSTEM_TIME_INFORMATION SysTimeInfo; SYSTEM_BASIC_INFORMATION SysBaseInfo; // get number of processors in the system status = NtQuerySystemInformation(SystemBasicInformation, &SysBaseInfo, sizeof(SysBaseInfo), NULL); if (status != NO_ERROR) { printf("Querying SystemBasicInformation failed: 0x%x\n", status); return; } // get new system time status = NtQuerySystemInformation(SystemTimeInformation, &SysTimeInfo, sizeof(SysTimeInfo), NULL); if (status!=NO_ERROR) { printf("Querying SystemTimeInformation failed: 0x%x\n", status); return; } // get new CPU times // http://www.codeproject.com/Articles/9113/Get-CPU-Usage-with-GetSystemTimes FILETIME ftIdleTime; FILETIME ftKernelTime; FILETIME ftUserTime; BOOL result = GetSystemTimes((LPFILETIME)&ftIdleTime, (LPFILETIME)&ftKernelTime, (LPFILETIME)&ftUserTime); if (result == FALSE) { printf("GetSystemTimes failed\n"); return; } unsigned long long systemTime = FileTimeToInt64(ftKernelTime) + FileTimeToInt64(ftUserTime); unsigned long long idleTime = FileTimeToInt64(ftIdleTime); // if it's a first call - skip it if (liOldIdleTime != 0) { // CurrentValue = NewValue - OldValue __int64 diffIdleTime = idleTime - liOldIdleTime; __int64 diffSystemTime = systemTime - liOldSystemTime; dbCpuTimePercent = (1.0f - ((diffSystemTime > 0) ? ((float)diffIdleTime) / diffSystemTime : 0)) * 100; } // store new times liOldIdleTime = idleTime; liOldSystemTime = systemTime; } else { printf("NtQuerySystemInformation or GetSystemTimes functions not available\n"); } }
void PowerStats::GetWinCPUTime(ULARGE_INTEGER &cpu_time) { FILETIME idle_time, kernel_time, user_time; if (GetSystemTimes(&idle_time, &kernel_time, &user_time)) { ULARGE_INTEGER k, u, i, total; k.LowPart = kernel_time.dwLowDateTime; k.HighPart = kernel_time.dwHighDateTime; u.LowPart = user_time.dwLowDateTime; u.HighPart = user_time.dwHighDateTime; i.LowPart = idle_time.dwLowDateTime; i.HighPart = idle_time.dwHighDateTime; total.QuadPart = (k.QuadPart + u.QuadPart); cpu_time.QuadPart = total.QuadPart - i.QuadPart; } }
WinCPUUsage::WinCPUUsage() : CPUUsage() , m_startSysIdle() , m_startSysKernel() , m_startSysUser() , m_startProcKernel() , m_startProcUser() { // Remember current CPU statistics FILETIME createTime, exitTime; GetSystemTimes(&m_startSysIdle, &m_startSysKernel, &m_startSysUser); GetProcessTimes(GetCurrentProcess(), &createTime, &exitTime, &m_startProcKernel, &m_startProcUser); }
int test_Cpu(loadInfo *pval) { ULONGLONG Sys_KernelTime_Diff; ULONGLONG Sys_UserTime_Diff; ULONGLONG Sys_IdleTime_Diff; ULONGLONG Proc_KernelTime_Diff; ULONGLONG Proc_UserTime_Diff; ULONGLONG nTotalSys; ULONGLONG nTotalProc; ULONGLONG nTotalMachine; GetSystemTimes(&Sys_IdleTime, &Sys_KernelTime, &Sys_UserTime); GetProcessTimes(GetCurrentProcess(),&Proc_Creationtime,&Proc_IdleTime, &Proc_KernelTime, &Proc_UserTime); Sys_KernelTime_Diff = SubtractTimes(Sys_KernelTime, Prev_Sys_KernelTime); Sys_UserTime_Diff = SubtractTimes(Sys_UserTime, Prev_Sys_UserTime); Sys_IdleTime_Diff = SubtractTimes(Sys_IdleTime, Prev_Sys_IdleTime); Proc_KernelTime_Diff = SubtractTimes(Proc_KernelTime, Prev_Proc_KernelTime); Proc_UserTime_Diff = SubtractTimes(Proc_UserTime, Prev_Proc_UserTime); nTotalSys = Sys_KernelTime_Diff + Sys_UserTime_Diff; nTotalProc = Proc_UserTime_Diff + Proc_KernelTime_Diff; nTotalMachine = (Sys_KernelTime_Diff + Sys_UserTime_Diff)-Sys_IdleTime_Diff; if (nTotalSys > 0) { pval->iocLoad=((100.0 * nTotalProc) / nTotalSys); pval->cpuLoad = ((100.0 * nTotalMachine) /nTotalSys ); } Prev_Ticks=Ticks; Prev_Proc_IdleTime = Proc_IdleTime; Prev_Proc_KernelTime = Proc_KernelTime; Prev_Proc_UserTime = Proc_UserTime; Prev_Sys_IdleTime = Sys_IdleTime; Prev_Sys_KernelTime = Sys_KernelTime; Prev_Sys_UserTime = Sys_UserTime; return 0; }
float getCpuUsage() //获取CPU的占用率 { #if _WIN32_WINNT < 0x0501 return 0.0f; #else static FILETIME prevSysKernel, prevSysUser; static FILETIME prevProcKernel, prevProcUser; static bool isFirstRun = true; FILETIME sysIdle, sysKernel, sysUser; FILETIME procCreation, procExit, procKernel, procUser; if (!GetSystemTimes(&sysIdle, &sysKernel, &sysUser) || !GetProcessTimes(GetCurrentProcess(), &procCreation, &procExit, &procKernel, &procUser)) {// can't get time info so return return -1.; } // check for first call if (isFirstRun) { isFirstRun = false; // save time info before return prevSysKernel.dwLowDateTime = sysKernel.dwLowDateTime; prevSysKernel.dwHighDateTime = sysKernel.dwHighDateTime; prevSysUser.dwLowDateTime = sysUser.dwLowDateTime; prevSysUser.dwHighDateTime = sysUser.dwHighDateTime; prevProcKernel.dwLowDateTime = procKernel.dwLowDateTime; prevProcKernel.dwHighDateTime = procKernel.dwHighDateTime; prevProcUser.dwLowDateTime = procUser.dwLowDateTime; prevProcUser.dwHighDateTime = procUser.dwHighDateTime; return -1.; } ULONGLONG sysKernelDiff = subtractTime(sysKernel, prevSysKernel); ULONGLONG sysUserDiff = subtractTime(sysUser, prevSysUser); ULONGLONG procKernelDiff = subtractTime(procKernel, prevProcKernel); ULONGLONG procUserDiff = subtractTime(procUser, prevProcUser); ULONGLONG sysTotal = sysKernelDiff + sysUserDiff; ULONGLONG procTotal = procKernelDiff + procUserDiff; return (float)((100.0 * procTotal) / sysTotal); #endif }
static int uptime_gettext(int tag, char *buf) { /* The file contains two numbers: * The first is the total number of seconds the system has been up. * The second is the total number of seconds each core has spent idle. * On multi-core systems, the second number may be greater than the first. */ uint64_t total = GetTickCount64() / 100ULL; LARGE_INTEGER idle_time, kernel_time, user_time; GetSystemTimes((FILETIME *)&idle_time, (FILETIME *)&kernel_time, (FILETIME *)&user_time); uint64_t idle = idle_time.QuadPart / (TICKS_PER_SECOND / 100); return ksprintf(buf, "%llu.%02u %llu.%02u\n", total / 100ULL, (uint32_t)(total % 100ULL), idle / 100ULL, (uint32_t)(idle % 100ULL)); }
bool get_times_since_last_call(float &idle_frac, float &kernel_frac, float &user_frac) { std::uint64_t idle, kernel, user; #ifdef _MSC_VER if (!GetSystemTimes(reinterpret_cast<PFILETIME>(&idle), reinterpret_cast<PFILETIME>(&kernel), reinterpret_cast<PFILETIME>(&user))) return false; #elif defined _linux FILE *fstat = fopen("/proc/stat", "r"); if (fstat == NULL) { perror("fopen(\"/proc/stat\") failed"); return 0; } long unsigned int cpu_time[7]; if (std::fscanf(fstat, "%*s %lu %lu %lu %lu %lu %lu %lu", &cpu_time[0], &cpu_time[1], &cpu_time[2], &cpu_time[3], &cpu_time[4], &cpu_time[5], &cpu_time[6]) == EOF) { fclose(fstat); return 0; } fclose(fstat); user = cpu_time[0] + cpu_time[1]; kernel = cpu_time[2] + cpu_time[5] + cpu_time[6]; idle = cpu_time[3] + cpu_time[4]; #endif auto d_user = user - old_user; auto d_kernel = kernel - old_kernel; auto d_idle = idle - old_idle; if (!d_user) return false; float total = static_cast<float>(d_user + d_kernel + d_idle); idle_frac = static_cast<float>(d_idle) / total; kernel_frac = static_cast<float>(d_kernel) / total; user_frac = static_cast<float>(d_user) / total; old_idle = idle; old_kernel = kernel; old_user = user; return true; }
void CCPULoad::readSystemValues(ULARGE_INTEGER *sysIdle, ULARGE_INTEGER *sysKernel, ULARGE_INTEGER *sysUser) { FILETIME ft_sys_idle; FILETIME ft_sys_kernel; FILETIME ft_sys_user; if (!GetSystemTimes(&ft_sys_idle, &ft_sys_kernel, &ft_sys_user)) { std::stringstream Message; Message << "GetSystemTimes failed with status:"; Message << std::hex << GetLastError(); shared::exception::CException(Message.str()); } CopyMemory(sysIdle, &ft_sys_idle, sizeof(FILETIME)); // Could been optimized away... CopyMemory(sysKernel, &ft_sys_kernel, sizeof(FILETIME)); // Could been optimized away... CopyMemory(sysUser, &ft_sys_user, sizeof(FILETIME)); // Could been optimized away... }
/*----------------------------------------------------------------------------- -----------------------------------------------------------------------------*/ void CPagetestBase::GetCPUTime(FILETIME &cpu_time, FILETIME &total_time) { FILETIME idle_time, kernel_time, user_time; if (GetSystemTimes(&idle_time, &kernel_time, &user_time)) { ULARGE_INTEGER k, u, i, combined, total; k.LowPart = kernel_time.dwLowDateTime; k.HighPart = kernel_time.dwHighDateTime; u.LowPart = user_time.dwLowDateTime; u.HighPart = user_time.dwHighDateTime; i.LowPart = idle_time.dwLowDateTime; i.HighPart = idle_time.dwHighDateTime; total.QuadPart = (k.QuadPart + u.QuadPart); combined.QuadPart = total.QuadPart - i.QuadPart; cpu_time.dwHighDateTime = combined.HighPart; cpu_time.dwLowDateTime = combined.LowPart; total_time.dwHighDateTime = total.HighPart; total_time.dwLowDateTime = total.LowPart; } }
int devIocStatsInitCpuUtilization(loadInfo *pval) { GetSystemTimes(&Prev_Sys_IdleTime, &Prev_Sys_KernelTime, &Prev_Sys_UserTime); GetProcessTimes(GetCurrentProcess(),&Proc_Creationtime,&Prev_Proc_IdleTime, &Prev_Proc_KernelTime, &Prev_Proc_UserTime); myprocessid = GetCurrentProcessId(); #ifdef _WIN64 pval->noOfCpus = GetMaximumProcessorCount(ALL_PROCESSOR_GROUPS); #else pval->noOfCpus = strtol(getenv("NUMBER_OF_PROCESSORS"),NULL,10); #endif return 0; }
float GetCPUUsage(FILETIME *prevSysKernel, FILETIME *prevSysUser, FILETIME *prevProcKernel, FILETIME *prevProcUser, bool firstRun) { FILETIME sysIdle, sysKernel, sysUser; FILETIME procCreation, procExit, procKernel, procUser; if (!GetSystemTimes(&sysIdle, &sysKernel, &sysUser) || !GetProcessTimes(GetCurrentProcess(), &procCreation, &procExit, &procKernel, &procUser)) { // can't get time info so return return -1.; } // check for first call if (firstRun) { // save time info before return prevSysKernel->dwLowDateTime = sysKernel.dwLowDateTime; prevSysKernel->dwHighDateTime = sysKernel.dwHighDateTime; prevSysUser->dwLowDateTime = sysUser.dwLowDateTime; prevSysUser->dwHighDateTime = sysUser.dwHighDateTime; prevProcKernel->dwLowDateTime = procKernel.dwLowDateTime; prevProcKernel->dwHighDateTime = procKernel.dwHighDateTime; prevProcUser->dwLowDateTime = procUser.dwLowDateTime; prevProcUser->dwHighDateTime = procUser.dwHighDateTime; return -1.; } ULONGLONG sysKernelDiff = FixCPUTimings(sysKernel, *prevSysKernel); ULONGLONG sysUserDiff = FixCPUTimings(sysUser, *prevSysUser); ULONGLONG procKernelDiff = FixCPUTimings(procKernel, *prevProcKernel); ULONGLONG procUserDiff = FixCPUTimings(procUser, *prevProcUser); ULONGLONG sysTotal = sysKernelDiff + sysUserDiff; ULONGLONG procTotal = procKernelDiff + procUserDiff; return (float)((100.0 * procTotal) / sysTotal); }
FT_DECLARE(ftdm_status_t) ftdm_cpu_get_system_idle_time(struct ftdm_cpu_monitor_stats *p, double *idle_percentage) { FILETIME idleTime; FILETIME kernelTime; FILETIME userTime; int64_t i64UserTime; int64_t i64KernelTime; int64_t i64IdleTime; if (!GetSystemTimes(&idleTime, &kernelTime, &userTime)) { return FTDM_FAIL; } i64UserTime = (int64_t)userTime.dwLowDateTime | ((int64_t)userTime.dwHighDateTime << 32); i64KernelTime = (int64_t)kernelTime.dwLowDateTime | ((int64_t)kernelTime.dwHighDateTime << 32); i64IdleTime = (int64_t)idleTime.dwLowDateTime | ((int64_t)idleTime.dwHighDateTime << 32); if (p->valid_last_times) { int64_t i64User = i64UserTime - p->i64LastUserTime; int64_t i64Kernel = i64KernelTime - p->i64LastKernelTime; int64_t i64Idle = i64IdleTime - p->i64LastIdleTime; int64_t i64System = i64User + i64Kernel; *idle_percentage = 100.0 * i64Idle / i64System; } else { *idle_percentage = 100.0; p->valid_last_times = 1; } /* Remember current value for the next call */ p->i64LastUserTime = i64UserTime; p->i64LastKernelTime = i64KernelTime; p->i64LastIdleTime = i64IdleTime; /* Success */ return FTDM_SUCCESS; }
HOOKFUNC BOOL WINAPI MyGetSystemTimes(LPFILETIME lpIdleTime, LPFILETIME lpKernelTime, LPFILETIME lpUserTime) { debuglog(LCF_TIMEFUNC|LCF_TODO|LCF_UNTESTED|LCF_DESYNC, __FUNCTION__ " called.\n"); return GetSystemTimes(lpIdleTime, lpKernelTime, lpUserTime); }
/* ** Updates the current CPU utilization value. ** */ bool CMeasureCPU::Update() { if (!CMeasure::PreUpdate()) return false; if (m_Processor == 0) { BOOL status; FILETIME ftIdleTime, ftKernelTime, ftUserTime; // get new CPU's idle/kernel/user time status = GetSystemTimes(&ftIdleTime, &ftKernelTime, &ftUserTime); if (status == 0) return false; CalcUsage(Ft2Double(ftIdleTime), Ft2Double(ftKernelTime) + Ft2Double(ftUserTime)); } else if (c_NtQuerySystemInformation) { LONG status; ULONG bufSize = c_BufferSize; BYTE* buf = (bufSize > 0) ? new BYTE[bufSize] : NULL; int loop = 0; do { ULONG size = 0; status = c_NtQuerySystemInformation(SystemProcessorPerformanceInformation, buf, bufSize, &size); if (status == STATUS_SUCCESS || status != STATUS_INFO_LENGTH_MISMATCH) break; else // status == STATUS_INFO_LENGTH_MISMATCH { if (size == 0) // Returned required buffer size is always 0 on Windows 2000/XP. { if (bufSize == 0) { bufSize = sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION) * c_NumOfProcessors; } else { bufSize += sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION); } } else { if (size != bufSize) { bufSize = size; } else // ?? { bufSize += sizeof(SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION); } } delete [] buf; buf = new BYTE[bufSize]; } ++loop; } while (loop < 5); if (status != STATUS_SUCCESS) // failed { delete [] buf; return false; } if (bufSize != c_BufferSize) { // Store the new buffer size c_BufferSize = bufSize; } SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION* systemPerfInfo = (SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION*)buf; int processor = m_Processor - 1; CalcUsage(Li2Double(systemPerfInfo[processor].IdleTime), Li2Double(systemPerfInfo[processor].KernelTime) + Li2Double(systemPerfInfo[processor].UserTime)); delete [] buf; } else { return false; } return PostUpdate(); }
int main(int argc, char** argv) { #if !defined(_WIN32) && !defined(_WIN64) printf("Only Windows OS is supported.\n"); #else if(argc < 3) { printf("usage: %s <dir> <command>\n", argv[0]); return -1; } char path[512]; sprintf_s(path, 511, "%s\\%s.pid", argv[1], argv[2]); DWORD pid = 0; FILE* f = NULL; fopen_s(&f, path, "r"); if(!f) { fprintf(stderr, "Can't open file %s\n", path); } else { char* pidbuf[32]; int numread = fread(pidbuf, sizeof(char), 31, f); if(numread > 0) { pidbuf[numread] = '\0'; pid = atoi((const char*)pidbuf); } } if(pid > 0) { printf("ProcessID: %d\n", pid); HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, false, pid); if(h <= 0) { fprintf(stderr, "Process %d can't be opened.\n", pid); printf("ProcessUpTime: \n"); } else { //Process elapsed time. BIGTIME CreateTime, ExitTime, ElapsedTime, Now; FILETIME KernelTime, UserTime; GetProcessTimes(h, &CreateTime.ft, &ExitTime.ft, &KernelTime, &UserTime); if(ExitTime.li > CreateTime.li) ElapsedTime.li = ExitTime.li - CreateTime.li; else { GetSystemTimeAsFileTime(&Now.ft); ElapsedTime.li = Now.li - CreateTime.li; } unsigned elapsedsecs = (unsigned)(ElapsedTime.li/10000000); TSpan span(elapsedsecs); printf("ProcessUpTime: %d-%02d:%02d:%02d\n", span.d, span.h, span.m, span.s); } } else { printf("ProcessID: \nProcessUpTime: \n"); } //CPU usage BIGTIME idle1, kernel1, user1, idle2, kernel2, user2; GetSystemTimes(&idle1.ft, &kernel1.ft, &user1.ft); Sleep(1000); GetSystemTimes(&idle2.ft, &kernel2.ft, &user2.ft); int IdleTime = (int)(idle2.li - idle1.li); int TotalTime = (int)((kernel2.li + user2.li) - (kernel1.li + user1.li)); int idleRate = (int)(100.0 * IdleTime / TotalTime); printf("CPU-Idle: %d%%\n", idleRate); //Computer uptime LARGE_INTEGER ticks, unit; QueryPerformanceCounter(&ticks); QueryPerformanceFrequency(&unit); int secs = (int)(ticks.QuadPart/unit.QuadPart); TSpan u((int)secs); printf("ComputerUpTime: %d days, %d:%d\n", u.d, u.h, u.m); printf("---SpaceUsedAndFree---\n"); //Physical and virtual memory usage. MEMORYSTATUS memstatus; GlobalMemoryStatus(&memstatus); printf("Physical Memory: %d %d\nVirtual Memory: %d %d\n", (memstatus.dwTotalPhys - memstatus.dwAvailPhys)/1024, memstatus.dwAvailPhys/1024, (memstatus.dwTotalVirtual - memstatus.dwAvailVirtual)/1024, memstatus.dwAvailVirtual/1024); // Disk Usage char drivePath[] = "?:\\"; char driveName; for( driveName = 'A'; driveName <= 'Z'; driveName++ ) { drivePath[0] = driveName; int dtype = GetDriveTypeA(drivePath); if(dtype == DRIVE_FIXED || dtype == DRIVE_RAMDISK || dtype == DRIVE_REMOVABLE || dtype == DRIVE_CDROM) { ULARGE_INTEGER diskAvailStruct; ULARGE_INTEGER diskTotalStruct; diskAvailStruct.QuadPart = 0; diskTotalStruct.QuadPart = 0; GetDiskFreeSpaceExA(drivePath, &diskAvailStruct, &diskTotalStruct, 0); double DiskSize = diskTotalStruct.QuadPart / 1024.0; double FreeSize = diskAvailStruct.QuadPart / 1024.0; printf("%s: %.0f %.0f\n", drivePath, DiskSize - FreeSize, FreeSize); } } #endif return 0; }
HOOKFUNC BOOL WINAPI MyGetSystemTimes(LPFILETIME lpIdleTime, LPFILETIME lpKernelTime, LPFILETIME lpUserTime) { ENTER(); LOG() << "Warning: Not yet implemented!"; return GetSystemTimes(lpIdleTime, lpKernelTime, lpUserTime); }
INT32 CGSProcessInfo::GSGetTotalCPUUsage(INT32 &iCPU) { INT32 iRet = -1; #ifdef _WIN32 FILETIME preidleTime; FILETIME prekernelTime; FILETIME preuserTime; FILETIME idleTime; FILETIME kernelTime; FILETIME userTime; GetSystemTimes( &idleTime, &kernelTime, &userTime ); preidleTime = idleTime; prekernelTime = kernelTime; preuserTime = userTime ; //休眠1s后再获取 MSLEEP(1000); GetSystemTimes( &idleTime, &kernelTime, &userTime ); INT64 idle = CompareFileTime( preidleTime,idleTime); INT64 kernel = CompareFileTime( prekernelTime, kernelTime); INT64 user = CompareFileTime(preuserTime, userTime); //CPU利用率 iCPU = (kernel +user - idle) *100/(kernel+user); //CPU空闲率 INT64 cpuidle = ( idle) *100/(kernel+user); iRet = 0; #elif _LINUX DWORD total1; DWORD total2; DWORD user1; DWORD nice1; DWORD system1; DWORD idle1; DWORD iowait1; DWORD irq1; DWORD softirq1; DWORD user2; DWORD nice2; DWORD system2; DWORD idle2; DWORD iowait2; DWORD irq2; DWORD softirq2; char cpu[21]; char text[201]; FILE *fp; fp = fopen("/proc/stat", "r"); fgets(text, 200, fp); if(strstr(text, "cpu")) { sscanf(text, "%s%lu%lu%lu%lu", cpu, &user1, &nice1, &system1, &idle1, &iowait1, &irq1, &softirq1); } fclose(fp); total1 = (user1+nice1+system1+idle1+iowait1+irq1+softirq1); MSLEEP(1000); fp = fopen("/proc/stat", "r"); fgets(text, 200, fp); if(strstr(text, "cpu")) { sscanf(text, "%s%lu%lu%lu%lu", cpu, &user2, &nice2, &system2, &idle2, &iowait2, &irq2, &softirq2); } fclose(fp); total2 = (user2+nice2+system2+idle2+iowait2+irq2+softirq2); if ((total2 - total1) == 0) { iCPU = 0; } else { iCPU = (INT32)((user2-user1+nice2 - nice1 +system2 - system1)*10000)/(total2-total1); } iRet = 0; #endif return iRet; }
int llCommands::Loop(void) { #ifdef _MSC_VER __int64 time_statistics[LLCOM_MAX_WORKERS]; int time_statistics_cmd[LLCOM_MAX_WORKERS]; char *time_statistics_cmdname[LLCOM_MAX_WORKERS]; unsigned int time_statistics_pointer = 0; #endif //****************** //batch loop //****************** int com = 0; mesg->WriteNextLine(LOG_INFO, "****** Go into batch mode in %s ******", section); while (com > -2) { #ifdef _MSC_VER FILETIME idleTime; FILETIME kernelTime; FILETIME userTime; BOOL res = GetSystemTimes( &idleTime, &kernelTime, &userTime ); #endif #ifdef USE_CATCH try { #endif com = GetCommand(); #ifdef USE_CATCH } catch (char *str) { if (CurrentCommand) mesg->WriteNextLine(-LOG_FATAL, "Catched exception [%s] in [%s]", str, CurrentCommand); else mesg->WriteNextLine(-LOG_FATAL, "Catched exception [%s]", str); } catch (int str) { if (CurrentCommand) mesg->WriteNextLine(LOG_FATAL, "Catched exception [%i] in [%s]", str, CurrentCommand); else mesg->WriteNextLine(LOG_FATAL, "Catched exception [%i]", str); } catch (...) { if (CurrentCommand) mesg->WriteNextLine(LOG_FATAL, "Catched exception in [%s]", CurrentCommand); else mesg->WriteNextLine(LOG_FATAL, "Catched exception"); } #endif mesg->Dump(); #ifdef _MSC_VER FILETIME userTime_old = userTime; res = GetSystemTimes( &idleTime, &kernelTime, &userTime ); BOOL found = false; for (unsigned int ii=0; ii<time_statistics_pointer; ii++) { if (com == time_statistics_cmd[ii]) { ULARGE_INTEGER u1 = { userTime.dwLowDateTime, userTime.dwHighDateTime }; ULARGE_INTEGER u2 = { userTime_old.dwLowDateTime, userTime_old.dwHighDateTime }; time_statistics[ii] += u1.QuadPart - u2.QuadPart; found = true; } } if (!found && CurrentCommand) { ULARGE_INTEGER u1 = { userTime.dwLowDateTime, userTime.dwHighDateTime }; ULARGE_INTEGER u2 = { userTime_old.dwLowDateTime, userTime_old.dwHighDateTime }; time_statistics[time_statistics_pointer] = u1.QuadPart - u2.QuadPart; time_statistics_cmd[time_statistics_pointer] = com; time_statistics_cmdname[time_statistics_pointer] = _llUtils()->NewString((char*) CurrentCommand); time_statistics_pointer++; } #endif } std::cout << "****** Batch loop done ******" << std::endl; #ifdef _MSC_VER for (unsigned int ii=0; ii<time_statistics_pointer; ii++) { for (unsigned int jj=0; jj<time_statistics_pointer-1; jj++) { if (time_statistics[jj] < time_statistics[jj+1]) { __int64 time_statistics_tmp = time_statistics[jj]; char * time_statistics_cmdname_tmp = time_statistics_cmdname[jj]; time_statistics[jj] = time_statistics[jj+1]; time_statistics_cmdname[jj] = time_statistics_cmdname[jj+1]; time_statistics[jj+1] = time_statistics_tmp; time_statistics_cmdname[jj+1] = time_statistics_cmdname_tmp; } } } std::cout << "User time per command (sorted):" << std::endl; for (unsigned int ii=0; ii<time_statistics_pointer; ii++) { if (time_statistics[ii] > 1000000) std::cout << time_statistics_cmdname[ii] << ": " << (((double)time_statistics[ii]) /10000000.)<< " s" << std::endl; } #endif return 0; }
//---------------------------------------------------------------------------- // Function: SystemInfo // // Description: // Returns the resource information about the machine // // Returns: // EXIT_SUCCESS: On success // EXIT_FAILURE: otherwise int SystemInfo() { size_t vmemSize, vmemFree, memSize, memFree; PERFORMANCE_INFORMATION memInfo; SYSTEM_INFO sysInfo; FILETIME idleTimeFt, kernelTimeFt, userTimeFt; ULARGE_INTEGER idleTime, kernelTime, userTime; ULONGLONG cpuTimeMs; size_t size; LPBYTE pBuffer; PROCESSOR_POWER_INFORMATION const *ppi; ULONGLONG cpuFrequencyKhz; NTSTATUS status; ZeroMemory(&memInfo, sizeof(PERFORMANCE_INFORMATION)); memInfo.cb = sizeof(PERFORMANCE_INFORMATION); if(!GetPerformanceInfo(&memInfo, sizeof(PERFORMANCE_INFORMATION))) { ReportErrorCode(L"GetPerformanceInfo", GetLastError()); return EXIT_FAILURE; } vmemSize = memInfo.CommitLimit*memInfo.PageSize; vmemFree = vmemSize - memInfo.CommitTotal*memInfo.PageSize; memSize = memInfo.PhysicalTotal*memInfo.PageSize; memFree = memInfo.PhysicalAvailable*memInfo.PageSize; GetSystemInfo(&sysInfo); if(!GetSystemTimes(&idleTimeFt, &kernelTimeFt, &userTimeFt)) { ReportErrorCode(L"GetSystemTimes", GetLastError()); return EXIT_FAILURE; } idleTime.HighPart = idleTimeFt.dwHighDateTime; idleTime.LowPart = idleTimeFt.dwLowDateTime; kernelTime.HighPart = kernelTimeFt.dwHighDateTime; kernelTime.LowPart = kernelTimeFt.dwLowDateTime; userTime.HighPart = userTimeFt.dwHighDateTime; userTime.LowPart = userTimeFt.dwLowDateTime; cpuTimeMs = (kernelTime.QuadPart - idleTime.QuadPart + userTime.QuadPart)/10000; // allocate buffer to get info for each processor size = sysInfo.dwNumberOfProcessors * sizeof(PROCESSOR_POWER_INFORMATION); pBuffer = (BYTE*) LocalAlloc(LPTR, size); if(!pBuffer) { ReportErrorCode(L"LocalAlloc", GetLastError()); return EXIT_FAILURE; } status = CallNtPowerInformation(ProcessorInformation, NULL, 0, pBuffer, (long)size); if(0 != status) { fwprintf_s(stderr, L"Error in CallNtPowerInformation. Err:%d\n", status); LocalFree(pBuffer); return EXIT_FAILURE; } ppi = (PROCESSOR_POWER_INFORMATION const *)pBuffer; cpuFrequencyKhz = ppi->MaxMhz*1000; LocalFree(pBuffer); fwprintf_s(stdout, L"%Iu,%Iu,%Iu,%Iu,%u,%I64u,%I64u\n", vmemSize, memSize, vmemFree, memFree, sysInfo.dwNumberOfProcessors, cpuFrequencyKhz, cpuTimeMs); return EXIT_SUCCESS; }
GetCpuUseage::GetCpuUseage() { GetSystemTimes(&m_preidleTime, &m_prekernelTime, &m_preuserTime); Sleep(100); }