From /proc/$PID/stat, you can get the amount of cpu time a process has used in user and system mode (similar to times, but for other processes). If you examine this twice, with a few seconds of delay between them, you get the amount of time the cpu spent on it. You then divide this amount with the delay, and there you are. (Of course, on an smp machine you may or may not want to divide with the number of cpus, depending on what you mean by cpu-percent.)

There must be a faster wat though, as ps u can return the percent-cpu faster. As eXile has recommended, get procps from http://procps.sf.net/.


In reply to Re: Calculating percent cpu in linux? by ambrus
in thread Calculating percent cpu in linux? by suaveant

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.