Forum: Ruby Get CPU usage

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
7995848b62bf9c645e859060ba1c856c?d=identicon&s=25 Panda Beer (pandabeer)
on 2008-12-14 14:08
Hello everybody,

I would like to get the % of CPU usage of a current Ruby script.
For example, I would like to start my script like and allow it to get
and print this such as:

./application.rb
=> 12:10 => CPU usage is 3.2%
=> 12:15 => CPU usage is 3.1%
=> 12:20 => CPU usage is 3.1%
=> 12:25 => CPU usage is 3.5%

Have you got an idea? Many thanks.
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2008-12-14 15:25
(Received via mailing list)
On 14.12.2008 14:01, Panda Beer wrote:
> => 12:25 => CPU usage is 3.5%
>
> Have you got an idea? Many thanks.

$ ruby -e '10.times { 100000.times { 1 + 2 }; p Process.times }'
#<struct Struct::Tms utime=0.062, stime=0.046, cutime=0.0, cstime=0.0>
#<struct Struct::Tms utime=0.109, stime=0.046, cutime=0.0, cstime=0.0>
#<struct Struct::Tms utime=0.156, stime=0.046, cutime=0.0, cstime=0.0>
#<struct Struct::Tms utime=0.203, stime=0.046, cutime=0.0, cstime=0.0>
#<struct Struct::Tms utime=0.25, stime=0.046, cutime=0.0, cstime=0.0>
#<struct Struct::Tms utime=0.296, stime=0.046, cutime=0.0, cstime=0.0>
#<struct Struct::Tms utime=0.343, stime=0.046, cutime=0.0, cstime=0.0>
#<struct Struct::Tms utime=0.406, stime=0.046, cutime=0.0, cstime=0.0>
#<struct Struct::Tms utime=0.453, stime=0.046, cutime=0.0, cstime=0.0>
#<struct Struct::Tms utime=0.5, stime=0.046, cutime=0.0, cstime=0.0>

You could correlate that to real time that has passed.

$ ruby -e 't=Time.now; 10.times { sleep 2;
pt=Process.times;p((pt.utime+pt.stime)/(Time.now-t)) }'
0.015
0.00749812546863284
0.00499916680553241
0.00374953130858643
0.002999700029997
0.00249979168402633
0.00214270409256482
0.00187488281982376
0.00166657407921782
0.00149992500374981

robert@fussel ~
$ ruby -e 't=Time.now; 10.times {10_000.times {1+2};
pt=Process.times;p((pt.utime+pt.stime)/(Time.now-t)) }'
19.25
8.55555555555556
5.13333333333333
4.89473684210526
3.875
3.20689655172414
3.20588235294118
2.86842105263158
2.5952380952381
2.31914893617021

Obviously there is a factor missing...

robert@fussel ~

  robert
This topic is locked and can not be replied to.