tdevil76 has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, First, I am using a Redhat box with the latest version of Apache. I need to get the cpu usage at the end of each http request, and store it for the VirtualHost that requested it. I have no problem getting cpu usage from /proc/$pid/stat... the problem is timing. I need to record the cpu usage before another request comes in to the same apache process, so I am using an apache handler to put the process "on hold" until I can get the cpu usage. The problem is that stat does not get updated with the latest stats until after the apache process has completed the current request. I'm hoping there is some way to get the stat to update while the apache process is still running... I hope I've explained myself well ... any suggestions?

Replies are listed 'Best First'.
Re: CPU Usage by VirtualHost
by perrin (Chancellor) on Jun 09, 2007 at 03:31 UTC
      Stonehenge::Throttle uses the same /proc/pid/stats that I've been using ...
        What makes you think they don't get updated until after the request completes?
Re: CPU Usage by VirtualHost
by Util (Priest) on Jun 09, 2007 at 00:24 UTC

    I am fuzzy on whether the Apache handlers and processes are parent/child, siblings, single/same process, or something else. Perhaps the times function will do the job.

    times Returns a four-element list giving the user and system times, in seconds, for this process and the children of this process.
    ( $user, $system, $cuser, $csystem ) = times;

    This code shows that times does not wait until end-of-process or I/O operation to update its data source:

    $ perl -wle 'sub r{@t=times();push @out,qq{@t}} sub x{my $z; $z.=1 for + 1..1_000_000;} r; x; r; x; r;print for @out' 0 0 0 0 0.17 0 0 0 0.29 0 0 0

      The handlers are run in the same process as the apache process... I will check out times.
        SO, it looks like times() uses the same cpu times from the /proc filesystem that everything else uses. I wonder what I need to do (a signal that needs to be sent maybe) to get the /proc cpu usage stats to update....
Re: CPU Usage by VirtualHost
by moritz (Cardinal) on Jun 08, 2007 at 23:21 UTC
    Normally collecting CPU statistics is not the task of CGI scripts - maybe you could tell us why you need that?

    If you just want to monitor CPU usage, you could use collectd

      My client wants to collect statistics about the cpu usage based on the VirtualHost making the request on his server(s)
        But you are trying to measure the CPU usage at the time of the request, not the CPU usage of that a specific request used up.

        To measure that you'd need a process specific or even thread specific clock, depending on which apache worker model you use.