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

HI i am new at perl i have to wtite script for cpu utilization and i dont know what to do.Can any one suggest me how to write code??

Replies are listed 'Best First'.
Re: cpu utilization for unix os
by Propaganda.pm_rj (Acolyte) on Mar 31, 2013 at 22:27 UTC
Re: cpu utilization for unix os
by roboticus (Chancellor) on Apr 01, 2013 at 12:35 UTC

    panku55:

    One simple way to write script for CPU utilization would be something like this:

    #!/usr/bin/perl use strict; use warnings; while (1) { }

    However, that may not use enough CPU. You might try forking off a few dozen processes and have each of them slaving away on the busy loop. But as computers get faster and faster, one day soon an infinite loop will execute in just a few seconds. So I suggest you wrap the busy loop inside a few other busy loops to keep them running:

    #!/usr/bin/perl use strict; use warnings; while (1) { while (1) { while (1) { while (1) { } } } }

    Modern computers also have segmented themselves into various sections. The busy loop will keep the control-flow part of your CPU busy, but it won't do anything at all for your integer, logic and floating-point sections. So to give them some exercise, you'll want to add some other bits of work to do:

    #!/usr/bin/perl use strict; use warnings; my ($april, $fools) = (0, 0); while (1) { while (1) { while (1) { while (1) { if (rand > .5) { if (rand > .5) { $april *= .7 } else { $april /= . +5 } if (rand < .5) { $april += 4.5} else { $april -= 3 +.2 } } if (rand > .5) { if (rand > .5) { $fools *= 3 } else { $fools %= 13 + } if (rand < .5) { $fools += 5 } else { $fools -= 11 + } } } } } }

    Feel free to add some code to exercise the transcendental functions as well. Additionally, if you want increase your printer utilization as well, you might fork off a version of this code that prints its results. With a few more modules, you can increase your network utilization as well!

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

      And don't forget to download some more RAM if you need to run some of roboticus's scripts concurrently.

      ~Thomas~ 
      "Excuse me for butting in, but I'm interrupt-driven..."