?
Solved

Check memory usage (win32)

Posted on 2006-05-22
14
Medium Priority
?
1,282 Views
Last Modified: 2013-11-13
Hi

I'm looking for some Windows API functions which will tell me the current memory usage as viewed in the Performance tab of Task manager. Such as "Physical Memory" "Kernel memory"

Thanks

-mike
0
Comment
Question by:nerdmike
  • 4
  • 3
  • 2
  • +3
12 Comments
 
LVL 32

Expert Comment

by:jhance
ID: 16736666
These are all available via WMI (Windows Management Instrumentation).  Example:

http://www.computerperformance.co.uk/Logon/LogonScript_Memory.htm
0
 

Author Comment

by:nerdmike
ID: 16737114
I'm looking for API functions not some script
0
 
LVL 32

Expert Comment

by:jhance
ID: 16737134
The API is called WMI (as I said already!).

The script demonstrates the use of WMI.  It's available from any programming language including scripts.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:nerdmike
ID: 16737636
I don't see anything there that can help me

If you would be so kind to write a program in C which will print the total kernel memory (as shown on Task Manager->Peformance) on stdout, it will be helpful enough.
0
 
LVL 11

Expert Comment

by:kblack05
ID: 16737997
What's wrong with the mem command?

C:\WINDOWS\system32>mem


    655360 bytes total conventional memory
    655360 bytes available to MS-DOS
    633952 largest executable program size

   1048576 bytes total contiguous extended memory
         0 bytes available contiguous extended memory
    941056 bytes available XMS memory
           MS-DOS resident in High Memory Area

C:\WINDOWS\system32>mem /?
Displays the amount of used and free memory in your system.

MEM [/PROGRAM | /DEBUG | /CLASSIFY]

  /PROGRAM or /P   Displays status of programs currently loaded in memory.
  /DEBUG or /D     Displays status of programs, internal drivers, and other
                   information.
  /CLASSIFY or /C  Classifies programs by memory usage. Lists the size of
                   programs, provides a summary of memory in use, and lists
                   largest memory block available.

C:\WINDOWS\system32>
0
 

Author Comment

by:nerdmike
ID: 16738010
mem is not a win32 api function
0
 
LVL 32

Accepted Solution

by:
jhance earned 2000 total points
ID: 16738056
Here is a C++ souce code that does the same thing as the script I posted.  All WMI objects are access via the same mechanism.  I'm not at all sure exactly what WMI parameter is the one you are referring to in your question but I'm sure it's available via this interface since WMI is what the Task Manager uses to get its information.

The Microsoft Script-O-Matic, while script oriented, is an invaluable resource to use to explore the WMI namespace.  You might want to download it and check it out.


#ifndef _WIN32_DCOM
#define _WIN32_DCOM
#endif

#include <windows.h>
#include <objbase.h>
#include <atlbase.h>
#include <iostream>
#include <wbemidl.h>
#include <comutil.h>


int main( int argc, char** argv )
{
      HRESULT hr = CoInitializeEx( NULL, COINIT_MULTITHREADED );
      if ( FAILED( hr ) )
      {
            std::cerr << "COM initialization failed" << std::endl;
            return -1;
      }

      // setup process-wide security context
      hr = CoInitializeSecurity( NULL, // we're not a server
                                             -1, // we're not a server
                                             NULL, // dito
                                             NULL, // reserved
                                             RPC_C_AUTHN_LEVEL_DEFAULT, // let DCOM decide
                                             RPC_C_IMP_LEVEL_IMPERSONATE,
                                             NULL,
                                             EOAC_NONE,
                                             NULL );
      if ( FAILED( hr ) )
      {
            std::cerr << "Security initialization failed" << std::endl;
            return -1;
      }

      int result = 0;
      // we're going to use CComPtr<>s, whose lifetime must end BEFORE CoUnitialize is called
      {
            // connect to WMI
            CComPtr< IWbemLocator > locator;
            hr = CoCreateInstance( CLSID_WbemAdministrativeLocator, NULL,
                                          CLSCTX_INPROC_SERVER,
                                          IID_IWbemLocator, reinterpret_cast< void** >( &locator ) );
            if ( FAILED( hr ) )
            {
                  std::cerr << "Instantiation of IWbemLocator failed" << std::endl;
                  return -1;
            }

            // connect to local service with current credentials
            CComPtr< IWbemServices > service;
            hr = locator->ConnectServer( L"root\\cimv2", NULL, NULL, NULL,
                                                       WBEM_FLAG_CONNECT_USE_MAX_WAIT,
                                                       NULL, NULL, &service );
            if ( SUCCEEDED( hr ) )
            {
                  // execute a query
                  CComPtr< IEnumWbemClassObject > enumerator;

                  hr = service->ExecQuery( L"WQL", L"SELECT TotalPhysicalMemory FROM Win32_LogicalMemoryConfiguration",
                                                     WBEM_FLAG_FORWARD_ONLY, NULL, &enumerator );
                  if ( SUCCEEDED( hr ) )
                  {
                        // read the first instance from the enumeration (only one on single processor machines)
                        CComPtr< IWbemClassObject > TotalPhysicalMemory = NULL;
                        ULONG retcnt;
                        hr = enumerator->Next( WBEM_INFINITE, 1L, reinterpret_cast<IWbemClassObject**>( &TotalPhysicalMemory ), &retcnt );
                        if ( SUCCEEDED( hr ) )
                        {
                              if ( retcnt > 0 )
                              {
                                    // we have a processor installed :)
                                    // now extract a property value
                                    _variant_t var_val;
                                    hr = TotalPhysicalMemory->Get( L"TotalPhysicalMemory", 0, &var_val, NULL, NULL );
                                    if ( SUCCEEDED( hr ) )
                                    {
                                          _bstr_t str = var_val;
                                          std::cout << "TotalPhysicalMemory: " << str << std::endl;
                                    }
                                    else
                                    {
                                          std::cerr << "IWbemClassObject::Get failed" << std::endl;
                                          result = -1;
                                    }
                              }
                              else
                              {
                                    std::cout << "Enumeration empty" << std::endl;
                              }
                        }
                        else
                        {
                              std::cerr << "Error in iterating through enumeration" << std::cerr;
                              result = -1;
                        }
                  }
                  else
                  {
                        std::cerr << "Query failed" << std::endl;
                        result = -1;
                  }
            }
            else
            {
                  std::cerr << "Couldn't connect to service" << std::endl;
                  result = -1;
            }
      }
      CoUninitialize();

      return result;
}
0
 
LVL 32

Expert Comment

by:jhance
ID: 16738067
Oh, and one more time.  There is _NO_ WIN32 API function that returns what you are asking about.  You must use one of the methods that Microsoft has provided for that purpose.  So regardless of how many times you ask the same question, the answer will still be the same.  WMI is the way Microsoft intends you to get this information and, in fact, is the way they do it themselves.
0
 
LVL 30

Expert Comment

by:callrs
ID: 16739000
I'm wondering the same thing. But I'd ask for more..like how to get the memory usage of EACH APPLICATION, and each PROCESS, not just total memory usage. :) .. And how to do so not just in XP, but in Win98
0
 
LVL 1

Expert Comment

by:Bone99
ID: 16752018
Try this url:
http://www.codeproject.com/Purgatory/MemoryTracker.asp

I think the article will show you what you want to know.
0
 
LVL 14

Expert Comment

by:MilanKM
ID: 16831786
Here is a VB6 through which you can easily track the memory status. Just take a Timer control (Set Interval=1, Enabled=True) & 7 labels. Then just copy & paste the following code.

Private Declare Sub GlobalMemoryStatus Lib "kernel32" (lpBuffer As MEMORYSTATUS)
Private Type MEMORYSTATUS
        dwLength As Long
        dwMemoryLoad As Long
        dwTotalPhys As Long
        dwAvailPhys As Long
        dwTotalPageFile As Long
        dwAvailPageFile As Long
        dwTotalVirtual As Long
        dwAvailVirtual As Long
End Type

Private Sub Form_Load()
    Timer1.Enabled = True
End Sub

Private Sub Timer1_Timer()
Dim memStat As MEMORYSTATUS
    memStat.dwLength = Len(memStat)
    Call GlobalMemoryStatus(memStat)
    Label1.Caption = Format(memStat.dwMemoryLoad, "###,###,###")
    Label2.Caption = Format(memStat.dwTotalPhys, "###,###,###")
    Label3.Caption = Format(memStat.dwAvailPhys, "###,###,###")
    Label4.Caption = Format(memStat.dwTotalPageFile, "###,###,###")
    Label5.Caption = Format(memStat.dwAvailPageFile, "###,###,###")
    Label6.Caption = Format(memStat.dwTotalVirtual, "###,###,###")
    Label7.Caption = Format(memStat.dwAvailVirtual, "###,###,###")
    Label8.Caption = Format(memStat.dwTotalVirtual - memStat.dwAvailVirtual, "###,###,###")
End Sub

Thanks
MilanKM
0
 
LVL 14

Expert Comment

by:MilanKM
ID: 16831793
By the way GlobalMemoryStatus is a Win32 API under Kernal32 which is called in the program.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this post we will learn different types of Android Layout and some basics of an Android App.
Make the most of your online learning experience.
Simple Linear Regression
Six Sigma Control Plans

864 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question