Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

How to determine CPU and memory consumption from inside a process

I once had the task of determining the following performance parameters from inside a running application:

  • Total virtual memory available
  • Virtual memory currently used
  • Virtual memory currently used by my process
  • Total RAM available
  • RAM currently used
  • RAM currently used by my process
  • % CPU currently used
  • % CPU currently used by my process

The code had to run on Windows and Linux. Even though this seems to be a standard task, finding the necessary information in the manuals (WIN32 API, GNU docs) as well as on the Internet took me several days, because there's so much incomplete/incorrect/outdated information on this topic to be found out there.

In order to save others from going through the same trouble, I thought it would be a good idea to collect all the scattered information plus what I found by trial and error here in one place.

Answer*

Cancel
5
  • can this be modified for an external DLL function I can later call in c#?
    – Nico
    Commented Dec 2, 2015 at 12:55
  • 28
    The formatting of usage = is the most creative thing i have seen in a while, not readable at all but creative Commented May 26, 2016 at 14:45
  • 2
    Warning: the expression in the code above that calculates 'usage' is way off. If the system was idle, it would divide by zero. In case the idle time was equal to the user+kernel time, it would produce 0 rather than 50% as one would expect. Commented Dec 31, 2016 at 17:46
  • 2
    Also keep in mind that according to the current MSDN, kernel time also includes the idle time! Commented Dec 31, 2016 at 19:38
  • 1
    @sayyedmohsenzahraee: I haven't looked into the logic of it, just a comment on the code itself. 1) Use plain 64-bit variables instead of a union, i.e. ULONGLONG for VS instead of ULARGE_INTEGER. 2) You're overcomplicating things by calling CopyMemory(), just do ULONGLONG ul_sys_idle = *(ULONGLONG*)&ft_sys_idle; instead. It will be translated into a single CPU mov (or lea) instruction.
    – ahmd0
    Commented Dec 9, 2017 at 1:44