1

I made a program to get CPU usage in my C++ program. However I can't get anything else than

0.000000 sec user
0.000000 sec system

How can I get a usable value ?

I've tryed that code :

#include <stdio.h>
#include <sys/resource.h>
#include <sys/time.h>
#include <unistd.h>

void print_cpu_time() {
    struct rusage usage;
    getrusage (RUSAGE_SELF, &usage);
    printf ("CPU time: %ld.%06ld sec user, %ld.%06ld sec system\n",
    usage.ru_utime.tv_sec, usage.ru_utime.tv_usec,
    usage.ru_stime.tv_sec, usage.ru_stime.tv_usec);
}
Mike Telson
  • 127
  • 2
  • 2
  • 7
  • 1
    http://stackoverflow.com/questions/479722/how-to-get-current-cpu-and-ram-usage-in-c – gpasci Mar 28 '13 at 14:40
  • 3
    WHat is your "workload"? That is, what are you actually measuring? It is entirely possible that the work you've done by the time you get to getrusage is indeed zero time (because the granularity is, for example, 1ms) – Mats Petersson Mar 28 '13 at 14:43
  • Mats, your comment was nice. Indeed, my program just don't have enough workload ... How can I add some "dummy" workload to have a relevant value ? With a for(; ;) ? – Mike Telson Mar 28 '13 at 14:49
  • Open a big file, read it character-by-character. – Fred Foo Mar 28 '13 at 14:52
  • Okay, but I can't at the same time calculate the charge and read the file. I'm sorry but there is something there I don't really understand. How can I get a relevant value ? – Mike Telson Mar 28 '13 at 15:06
  • A long loop would clearly work. It all depends on what you are trying to achieve. Commonly, using "cpu usage" has to do with programs that use more than 1ms of CPU time. But a loop of 100 million (assuming it doesn't get optimized out) should take a few milliseconds at least. – Mats Petersson Mar 28 '13 at 15:07
  • Yeah, but even with 100 million, I still got 0.0000 CPU usage ... – Mike Telson Mar 28 '13 at 15:15
  • for (int i=0; i<100000; i++) printf("Howdy!\n"); // <-- a sample workload – Jeremy Friesner Mar 28 '13 at 15:53

0 Answers0