A C++ program to get CPU usage from command line in Linux

This article explains how to create a simple program

5 Comments

  1. markg85

    Just a thought.

    You are now doing string matching and parsing to get the cpu statistics, but there also seems to be c kernel functions for exactly that. It would save you the hassle of parsing /proc/stat and it will be quite a bit more efficient to use the c functions.

    Have a look in the stat implementation: https://github.com/torvalds/linux/blob/master/fs/proc/stat.c

    The downside is that your code will be bigger if you go that route and it will probably have to be recompiled if your kernel gets updated..

    Reply
    1. Davide Coppola (Post author)

      I haven’t looked into this much, but to the best of my knowledge programs in user space can’t call kernel functions.

      The only way to communicate with the kernel is using syscalls.

      Reply
      1. markg85

        I realized that right after posting my message 😉
        You would have to make a kernel module, expose a syscall and use that in user space.

        That would be quite a complicated piece of code for something seemingly simple.

        This does make me think.. Why don’t the /proc/* provide an output that is easy to parse. Like json or so. The output as is right now seems to be focused on human readability.

        Reply
        1. Davide Coppola (Post author)

          I am not a kernel developer, but I believe the philosophy behind it is providing information in a compact and “straight to the point” way. It’s low-level stuff after all.

          Parsing space-separated numbers is not that hard after all, as you can see in my (simple) example code. 🙂

          Reply
  2. phil

    just tried it on a raspberry pi, it shows high loads while the system monitor shows the oposite

    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *