[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1094
  • Last Modified:

Get CPU usage.

Hi,

I'm currently trying to code, in C++, something which will output the current CPU usage. Eventually, I'll be implementing it in with some Java (using JNI of course).

I'm unfortunately having some difficulties getting what I've tried so far to work (ie; coding something in C++ that does this) -- I've posted in the C++ TA, and fortunately have 'jkr' on the job .. but in the mean time, I was wondering if any of you lot have needed to implement some Native, in order to get the CPU usage -- if so, do you have some code that I could nick? :-)

Thanks,
Rob.
0
InteractiveMind
Asked:
InteractiveMind
3 Solutions
 
OBCTCommented:
I've never had to use this myself, however it looks pretty good.
http://www.codeproject.com/system/cpuusage.asp
0
 
aozarovCommented:
Not pretty but from java you can invoke external process and read its output (and that process can provide you the cpu information)
See: java.lang.Runtime#exec -> http://javaalmanac.com/cgi-bin/search/find.pl?words=exec
For windows you can invoke:
http://www.ss64.com/nt/tasklist.html
For Linux you can invoke:
/usr/bin/top
0
 
Mayank SAssociate Director - Product EngineeringCommented:
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!

 
InteractiveMindAuthor Commented:
> I've never had to use this myself, however it looks pretty good.
http://www.codeproject.com/system/cpuusage.asp

I've tried this one before, I'm also trying another piece of code which does something similar, from codeproject.com, however, this is what I'm having problems with; I believe that my C++ IDE doesn't support ATL headers. So before I try another compiler, I'm seeing if Jkr (C++ guru) can help..

> Not pretty but from java you can invoke external process and read its output (and that process can provide you the cpu information)
I think that I'll leave this one as a last resort :-)

> Have a look at the open-source Java profilers
I'll have a look through this a bit then..


Thanks all.
Rob.
0
 
makerpCommented:
heres some old code from a uni project - its very old !

/*
      Written By      :      Paul Maker
      Date            :      10/03/2001
      File            :      loadinfo.cpp
      Description      :      provides information on the current load of the
                              machine. You will have to configure two active
                              projects so that you can set one to link pdh.lib
                              and one that dont, also make sure the NT_BUILD or
                              9X_BUILD #define is present so it can choose the
                              right functions
*/

/* run times */
#include <assert.h>
#include <stdio.h>
#include <windows.h>

/* server code */
#include "svr_util.h"
#include "loadinfo.h"


/* the following pragma's are Visual C++ specific */
#ifdef _MSC_VER

#pragma warning(disable : 4244) /* C4244 warning expected from the
conversion between float and int in getCurrentLoad */
 
#pragma warning(disable : 4035) /* C4113 warning expected from the
theCycleCounter function */

#endif

/* creates two byes of data in the current text segment of the program
this is used to help get the CPU speed */
static inline unsigned __int64 theCycleCounter()
{      
      _asm    _emit 0x0F
    _asm    _emit 0x31 /* this implicetly pushes a return value
      on the stack, thats why i ignore the waring */
}

/* constructor */
LoadInfo::LoadInfo()
{
      cpu_speed = 0;
      access_control = CreateMutex(NULL,FALSE,NULL);

#ifdef __LOAD_INFO_DEBUG__
      printf("LoadInfo::LoadInfo -> object created\n");
#endif
}

/* de-structor */
LoadInfo::~LoadInfo()
{
/* do the right shutdown */
#ifdef _NT_BUILD
      PdhCloseQuery(&query_handle);
#elif _9x_BUILD
      RegOpenKeyEx(HKEY_DYN_DATA,"PerfStats\\StopStat",0,
                         KEY_ALL_ACCESS,&hkey);
      RegCloseKey(hkey);
#endif

      /* close the mutex handle */
      CloseHandle(access_control);

#ifdef __LOAD_INFO_DEBUG__
      printf("LoadInfo::~LoadInfo -> object destroyed\n");
#endif
}

/* initalizes the object */
int LoadInfo::init()
{
      /* work out the cpu speed first, this has provded to be very
      acurate (+/-  1 Mhz) */      
      unsigned __int64  start = 0;
      unsigned __int64  overhead = 0;

      start = theCycleCounter();
      Sleep(1000L);
      
      unsigned cpuspeed100 =
            (unsigned)((theCycleCounter() - start - overhead) / 10000);

      cpu_speed = cpuspeed100 / 100;      

#ifdef _NT_BUILD

      /* first open the PDH query */
      if(PdhOpenQuery(NULL,1,&query_handle) != ERROR_SUCCESS)
      {
            unhandled_error("error with PdhOpenQuery",GetLastError());
            return 0;
      }
      /* now add all the counters i want, only cou usage for
      the moment */
      if(PdhAddCounter(query_handle,CNTR_CPU_USAGE,(DWORD)&cpu_counter,
                               &cpu_counter.hCounter) != ERROR_SUCCESS)
      {
            unhandled_error("error with PdhAddCounter",GetLastError());
            return 0;
      }

#elif _9x_BUILD
      /* open the registry key */
    if(RegOpenKeyEx(HKEY_DYN_DATA,"PerfStats\\StartStat",0,
                            KEY_ALL_ACCESS,&hkey ) != ERROR_SUCCESS)
      {
            unhandled_error("error with RegOpenKeyEx",GetLastError());
            return 0;
      }
      /*  */
    dwDataSize = sizeof(DWORD);
    RegQueryValueEx(hkey,"KERNEL\\CPUUsage",NULL,&dwType,
                    (LPBYTE)&dwCpuUsage,&dwDataSize );
      /*  */
    RegCloseKey(hkey);
      /*  */
    if(RegOpenKeyEx(HKEY_DYN_DATA,"PerfStats\\StatData",0,KEY_READ,
                    &hkey) != ERROR_SUCCESS)
      {
            unhandled_error("error with RegOpenKeyEx",GetLastError());
            return 0;
      }
#endif

      /* all done */
      return 1;
}

/* gets the current load */
int LoadInfo::getCurrentLoad(struct _current_load_ *load)
{      
      assert(load != NULL);

      /* i serialized access to this because i dont know if the PDH
      query objects are thread safe, i need to find this out */
      WaitForSingleObject(access_control,INFINITE);

#ifdef _NT_BUILD

      /* collect the data */
      if(PdhCollectQueryData(query_handle) != ERROR_SUCCESS)
      {
            unhandled_error("error with PdhCollectQueryData",
                                    GetLastError());
            return 0;      
      }

      /* format it */
      PDH_FMT_COUNTERVALUE pdhFormattedValue;      
      if(PdhGetFormattedCounterValue(cpu_counter.hCounter,PDH_FMT_LONG,
                                                   NULL,&pdhFormattedValue) != ERROR_SUCCESS)
      {
            unhandled_error("error with PdhGetFormattedCounterValue",
                                    GetLastError());
            return 0;
      }      
      load->cpu_load = cpu_counter.lValue = pdhFormattedValue.longValue;      

#elif _9x_BUILD

      dwDataSize = sizeof(DWORD);
    RegQueryValueEx(hkey,"KERNEL\\CPUUsage",NULL,&dwType,
                         (LPBYTE)&dwCpuUsage,&dwDataSize);

      load->cpu_load = dwCpuUsage;

#endif

      load->cpu_speed = cpu_speed;

      /* work out the proportional mhz free */
      load->free_MHZ =
            cpu_speed - (((float)cpu_speed / 100) * load->cpu_load);

      /* get the free physical memory, this works on all 32bit Windows
      platforms */
      memory.dwLength = sizeof(MEMORYSTATUS);
      GlobalMemoryStatus(&memory);      
      load->free_memory_bytes = memory.dwAvailPhys;

      /* let another thread in */
      ReleaseMutex(access_control);

      return 1;
}
0
 
Jim CakalicSenior Developer/ArchitectCommented:
Hi,

Have you seen this article at JavaWorld?
http://www.javaworld.com/javaqa/2002-11/01-qa-1108-cpu_p.html

Regards,
Jim
0
 
neonlinesCommented:

/*********************************************************
*   FUNCTION NAME   :    LoadAverage                                                              *
*   INPUT           :    NONE                                                                     *
*   FUNCTION        :    To calculate the Load of The Memory                                      *
*                        Execute the system command                                               *
*                        Get the 16,17 and 18 fileds from the outpur                              *
*                        Calculate the average of the three values                                *
*                        Return the value                                                         *
*   OUTPUT          :    Average Load Of Memroy                                                   *
*************************************************************/

float LoadAverage()
{
    float LoadAve=0.0;
    FILE *fd1;
    char logstr[300];
    char logstring[500];
    char line[200];
    memset(logstr,0x00,sizeof(logstr));

    sprintf(logstr,"uptime | awk '{ for (i = NF; i > (NF-3); --i) print $i }'| tr \"[,]\" \"[ ]\"");

    fd1 = popen(logstr,"r"); //Executing the system command uptime
    if (fd1 ==(FILE *)0) //if unable to open the file, popen fails
    {
          memset(logstring,0x00,sizeof(logstring));
          sprintf(logstring,"popen failure,unable execute uptime sysfn...error<%s>",strerror(errno));
//          LogFile->logMesg(logstring);
          return -1;
    }

    while( (fgets(line,200,fd1) )!= NULL)
    {
          LoadAve=LoadAve + atof(line);
    }
    if( pclose(fd1)< 0 )
    {
          memset(logstring,0x00,sizeof(logstring));
          sprintf(logstring,"pclose failure...error<%s>",strerror(errno));
//          LogFile->logMesg(logstring);
    }

    LoadAve = LoadAve/3.0;
    return LoadAve;
}

0
 
neonlinesCommented:

Using psinfo_t structure u can get CPU usage

        psinfo_t ps;                            // Declaring a variable for psinfo_t structure



//CPU
(double)ps.pr_pctcpu/300

//Used
ps.pr_rssize;

//Percentage of Memory Used  
100 - (((alloc - used)*100)/alloc);
0
 
InteractiveMindAuthor Commented:
neonlines:

> "OUTPUT          :    Average Load Of Memory"

I'm after the CPU usage ... does your code provide that functionality?


Thank you.
0
 
neonlinesCommented:
Ya sure,

Just check the command "uptime" and it displayes 3 timesas follows

$ uptime
  9:20am  up 1 day(s), 14:20,  24 users,  load average: 0.77, 0.84, 0.87
$

I taken three times  0.77, 0.84, 0.87 and calculated the average


0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now