6

Using C++, is there a way I could get basic information about the computer?

For example, is there a way I could check how much memory is being used (by the whole computer not just my computer), the total memory available, virtual memory usage, CPU usage, networks stats and so on?

I am using Mac OS X v10.6 (Snow Leopard), but I would prefer a solution that could be implemented for all Mac OSs (for example, Mac OS X v10.7 (Lion)).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
fdh
  • 5,256
  • 13
  • 58
  • 101
  • Just for the record you only care about portability on different Mac platforms, instead of a general portable solution? c++ itself doesn't offer such functionality, so any solution is going to be more or less plattform dependent – Grizzly Jan 05 '12 at 02:04
  • A general portable solution would be perfect, but as you mentioned the solution would probably be platform dependent. If possible I would prefer a platform independent solution but since that isn't likely I can settle for portability on different Mac platforms. – fdh Jan 05 '12 at 02:12
  • Whoever voted the question down, justify yourself. Do not vote down questions without giving the cause of the problem. – fdh Jan 05 '12 at 02:18
  • possible duplicate of [Determine Process Info Programmatically in Darwin/OSX](http://stackoverflow.com/questions/220323/determine-process-info-programmatically-in-darwin-osx) Check out `proc_pidinfo` and `host_statistics` – David Gelhar Jan 05 '12 at 02:21
  • @DavidGelhar I have requested a variety of statistics not requested for in that question. The question specifically addresses CPU usage while I need assistance with a variety of other stats including virtual memory and network stats-both of which the question does not address. – fdh Jan 05 '12 at 02:24
  • 1
    I haven't voted it down, but if I'd have to guess I'd say its because your question isn't really good, meaning that its way to broad (what exactly are "basic information", telling you how to retrieve just about anything would take hours (or more). Furthermore you didn't really specify in your question what platforms you are interested in (only implied). Telling us what you need the informations for typically helps too. – Grizzly Jan 05 '12 at 02:25
  • 2
    I'm voting this down because there's no demonstration of effort on your part whatsoever. I don't use OS X, but 90 seconds of Googling yielded the answer to this question even using vague terminology... – ildjarn Jan 05 '12 at 02:47
  • @Grizzly The reason my question is vague is because I have absolutely no experience in this and have no idea how to retrieve this kind of information. I have provided examples of the kind of information I am looking for - I can't really expand because of my unfamiliarity. I can't really disclose why I need the information but I don't see how that would relate since I am asking for retrieval not the processing of the information. If more information is required I would gladly provide it, I would just prefer if people asked for something specific rather than simply voting the question down. – fdh Jan 05 '12 at 02:47
  • @ildjarn I already googled the question, but I either was completely lost with the answers (had no idea what they were talking about) or the question didn't provide all the information I was asking for. For example the link David provided had me completely lost as I have absolutely no idea how PID's could be used to retrieve this kind of information. The answer didn't go into detail which confused me. – fdh Jan 05 '12 at 02:50
  • I doubt anyone is going to post a tutorial of how to use POSIX APIs from the ground up. If you don't know how to use process IDs, then that warrants another, separate question. Expecting one all-encompassing answer for this is not realistic. – ildjarn Jan 05 '12 at 02:52
  • @ildjarn I do not expect a complete tutorial on PIDs or the POSIX API but I am simply hoping for a nudge in the right direction. Maybe a link to somewhere that explains this in detail or even something that could just get me started. (i.e. a few function prototypes with a brief description) – fdh Jan 05 '12 at 02:56
  • @Farhad: You shouldn't tell people what to do when you're new and asking for free help. – Lightness Races in Orbit Jan 05 '12 at 03:10
  • This website isn't for "nudges in the right direction". It's neither a forum, nor a chatroom. It's a Q&A website. There are plenty of _other_ places for this kind of **discussion**. – Lightness Races in Orbit Jan 05 '12 at 03:11
  • @LightnessRacesinOrbit I do not expect a discussion. Ildjarn claimed that it isn't possible to post a complete tutorial which is why I asked for a link to somewhere that could provide me with the information I need. That doesn't qualify as a discussion- it would just refer me to an answer outside of the scope of this webiste. – fdh Jan 05 '12 at 03:16
  • @Farhad: Then you're looking for a search engine. This isn't that, either. – Lightness Races in Orbit Jan 05 '12 at 03:22
  • @LightnessRacesinOrbit If you checked my previous comments you would have already noted that I did use a "search engine". However I was not satisfied with the results, which is why I am consulting a programming Q&A site in hope that people could provide an understandable answer and if not possible suggest a good tutorial that would serve as an answer to this question (sometimes fellow programmers experiences are more useful than "search engines") – fdh Jan 05 '12 at 03:28
  • @Farhad: Next time please read the FAQ. We're not here to cater to your every whim. – Lightness Races in Orbit Jan 05 '12 at 03:33
  • @LightnessRacesinOrbit I agree, but you are here to share knowledge that can assist programmers with related problems and create a community that is helpful and useful. By dismissing a question and asking the OP to find help elsewhere you are defying the purpose of the site - to HELP. – fdh Jan 05 '12 at 03:41
  • 3
    @Farhad: While we are here to share knowledge and all that, it's common courtesy that someone asking a question makes at least some effort to find out for him/herself. Besides you have told us neither what information you need nor what you need them for (from which someone more experienced might be able to infer what you need, if you don't know yourself). Generally this site is for concrete question which (hopefully) have definite answers instead of requests which boil down to "please do all the work for me". Look at http://stackoverflow.com/questions/how-to-ask – Grizzly Jan 05 '12 at 14:43
  • @Farhad: The purpose of the site is to generate questions and answers. That they help people is a corollary. I'm not going to help you find the best places to eat in Seattle, either. – Lightness Races in Orbit Jan 05 '12 at 16:12

2 Answers2

11

For system-wide memory usage information under Mac OS X, open and read the file /usr/bin/vm_stat. Something like this:

static double ParseMemValue(const char * b)
{
    while((*b)&&(isdigit(*b) == false))
        b++;
    return isdigit(*b) ? atof(b) : -1.0;
}

// Returns a number between 0.0f and 1.0f, with 0.0f meaning all RAM is available, and 1.0f meaning all RAM is currently in use
float GetSystemMemoryUsagePercentage()
{
    FILE * fpIn = popen("/usr/bin/vm_stat", "r");
    if (fpIn)
    {
        double pagesUsed = 0.0, totalPages = 0.0;
        char buf[512];
        while(fgets(buf, sizeof(buf), fpIn) != NULL)
        {
            if (strncmp(buf, "Pages", 5) == 0)
            {
                double val = ParseMemValue(buf);
                if (val >= 0.0)
                {
                    if ((strncmp(buf, "Pages wired",  11) == 0) ||
                        (strncmp(buf, "Pages active", 12) == 0)
                       )

                        pagesUsed += val;

                    totalPages += val;
                }
            }
            else
              if (strncmp(buf, "Mach Virtual Memory Statistics", 30) != 0)
                  break; // Stop at "Translation Faults". We don't care
                         // about anything at or below that
        }
        pclose(fpIn);

        if (totalPages > 0.0)
            return (float) (pagesUsed/totalPages);
    }
    return -1.0f;  // Indicate failure
}

For a CPU usage indicator, do something like this:

#include <mach/mach_init.h>
#include <mach/mach_error.h>
#include <mach/mach_host.h>
#include <mach/vm_map.h>

static unsigned long long _previousTotalTicks = 0;
static unsigned long long _previousIdleTicks = 0;

// Returns 1.0f for "CPU fully pinned", 0.0f for "CPU idle", or somewhere in between
// You'll need to call this at regular intervals, since it measures the load between
// the previous call and the current one.
float GetCPULoad()
{
    host_cpu_load_info_data_t cpuinfo;
    mach_msg_type_number_t count = HOST_CPU_LOAD_INFO_COUNT;
    if (host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO, (host_info_t)&cpuinfo, &count) == KERN_SUCCESS)
    {
        unsigned long long totalTicks = 0;
        for(int i=0; i<CPU_STATE_MAX; i++)
            totalTicks += cpuinfo.cpu_ticks[i];
        return CalculateCPULoad(cpuinfo.cpu_ticks[CPU_STATE_IDLE], totalTicks);
    }
    else
       return -1.0f;
}

float CalculateCPULoad(unsigned long long idleTicks, unsigned long long totalTicks)
{
    unsigned long long totalTicksSinceLastTime = totalTicks-_previousTotalTicks;
    unsigned long long idleTicksSinceLastTime  = idleTicks-_previousIdleTicks;
    float ret = 1.0f-((totalTicksSinceLastTime > 0) ? ((float)idleTicksSinceLastTime)/totalTicksSinceLastTime : 0);
    _previousTotalTicks = totalTicks;
    _previousIdleTicks  = idleTicks;
    return ret;
}

For network statistics, I don't know the solution (other than maybe to run netstat and parse the results somehow... it depends on what network statistics you are interested in I suppose).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234
-5

First off, if you are focusing on Mac OS only, then the language of choice should be Objective-C.

Steps you need to follow

  1. Learn Objective-C. It is not really that hard. I come from a C++ background myself and after a few weeks of working on the platform with this language I became rather fluent
  2. Check the Mac OS X developer library: Mac OS X Developer Library
  3. Check out this
  4. And this
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
CStreel
  • 2,642
  • 2
  • 19
  • 37
  • 6
    `the language of choice should be Objective - C` Why? Isn't this highly subjective? Can you back up your assertion? – Lightness Races in Orbit Jan 05 '12 at 03:11
  • Thanks! Just wondering, but I intent to eventually migrate the program to Windows too, but not for a couple of months at least. So should I still write the program in Obj-C? Because if I wrote in C++ I feel it would be easier to transfer to Windows later on. – fdh Jan 05 '12 at 03:12
  • @LightnessRacesinOrbit I believe he suggests Objective - C because Obj-C is the language generally used on Mac OS- much like Windows choose C# as their language Obj-C is the choice of Apple. Many of the system libraries probably have a better Obj-C API. – fdh Jan 05 '12 at 03:13
  • 2
    @Farhad: That's great but it should come from him and it should be in the answer. He's making it out to be a _fact_, when it is not. Much like "Windows choose C# as their language" is quite narrow-minded. – Lightness Races in Orbit Jan 05 '12 at 03:14
  • @LightnessRacesinOrbit Actually Windows does encourage use of C# over other languages - several of its API's are made specifically for C#- by saying they choose C# as their language I mean't they encourage usage of C# over other languages on their platforms through more C# APIs. – fdh Jan 05 '12 at 03:19
  • @LightnessRacesinOrbit checkout Apples Developer Library, "language of choice" is much more objective, personally im a C++ Developer – CStreel Jan 05 '12 at 03:19
  • @CStreel: How on earth is that objective? That's Apple's personal choice. – Lightness Races in Orbit Jan 05 '12 at 03:21
  • @Farhad: What Microsoft promotes and what "Windows developers prefer" (if any such generalisation can be formed, which I seriously doubt) are completely separate things. – Lightness Races in Orbit Jan 05 '12 at 03:21
  • @LightnessRacesinOrbit If one language has more comprehensive APIs that another languages for a specific platform that language would be prefereable to write in on that platform. When developing software the language most efficient on that platform is generally more important that what the user prefers because several more features can be implemented in certain languages. And "Apples personal choice" does effect what language is best for that platform because if the creator of an OS is leaning towards a certain language, writing code in that language would be more efficient. – fdh Jan 05 '12 at 03:25
  • @Farhad exactly, and language of choice means its a choice not a "You Must use this language" – CStreel Jan 05 '12 at 03:27
  • *sigh* I really can't be bothered any more. Good luck to the both of you. – Lightness Races in Orbit Jan 05 '12 at 03:33
  • whats with the sigh, Is the only thing u disagree with me on is the "Language of Choice" statement? – CStreel Jan 05 '12 at 04:18
  • @CStreel Do you suggest I use Obj-C or C++ since I hope to eventually move the program to Windows too? Because as you said Obj-C would be preferable on Mac but if I wrote it in C++ it would be easier to migrate to Windows. What do you suggest? – fdh Jan 05 '12 at 04:24
  • There would be a lot more work involved in that. There are likely already libraries that have solved the cross-platform issue. I haven't done any multi-platform work before so i am unable to comment on that – CStreel Jan 05 '12 at 04:43