Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Get CPU Usage with GetSystemTimes

0.00/5 (No votes)
20 Dec 2004 2  
How to get CPU usage with GetSystemTimes
In this article, you will find a solution for getting CPU usage with the help of GetSystemTimes.

Introduction

Since a very long time, a lot of people wanted to get the CPU usage from the computer.

You've a lot of ways to do this like calling registry like key or PerfCounter. But TaskManager doesn't call any of these ... If you're looking from the import table of TaskManager, you can find:

ntdll.dll
  Import Adress Table: 0x00001414
  Import Name Table: 0x00013C2C
      0x7C90E213 260 NtQueryVirtualMemory
      0x7C90DDF9 209 NtOpenThread
      0x7C90D586 103 NtClose
      ....
      0x7C90E1AA 255 NtQuerySystemInformation
      .... 

So there is no other solution to have this information to dig into undocumented NtQuerySystemInformation. With this nice warning at the beginning of the article: [NtQuerySystemInformation is available for use in Windows 2000 and Windows XP. It may be altered or unavailable in subsequent versions. Applications should use the alternate functions listed in this topic.]

No other solution?

Well, GetSystemTimes is a good function if you have the requirements:

Client         Requires Windows XP SP1. 
Server         Requires Windows Server 2003. 
Header         Declared in Winbase.h; include Windows.h.
Library        Link to Kernel32.lib.
DLL            Requires Kernel32.dll. 

How to Use It?

Call this:

FILETIME idleTime;
FILETIME kernelTime;
FILETIME userTime;
BOOL res = GetSystemTimes( &idleTime, &kernelTime, &userTime );

and voilĂ , you have almost what you need.

Now you have to poll this function and make a little calculus.

usr = userTime - last_userTime;
ker = kernelTime - last_kernelTime;
idl = idleTime - last_idleTime;

System time is:

sys = kerl + usr

idleTime is the rest because "System Idle" process is taking 100 % of CPU.

So CPU is:

cpu = int( (sys - idl) *100 / sys );

Conclusion

It was a very long wait before Microsoft gave us this function. Now it's done but there is still one problem. For multiple processor system, you don't have the right information.

In the sample, you can find the use of GetSystemTimes and GetProcessTimes and a little class to do everything.

class CPU
{
public:
  CPU( void );
  ~CPU( void );

  // return :
  // % of cpu usage for this process 
  // % cpu systemUsage 
  // uptime for this process
  int GetUsage( int* pSystemUsage, TKTime* pUpTime );

History

  • 20th December, 2004: Initial version

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here