0

My code has two jobs, the first consumes CPU 0.3%, the second consumes CPU 80%. The two jobs are repeatly worked like this:

while True:
  job1()
  job2()

I find after the first loop, the CPU consumption not down even if it worked in job1(), the consumption is always 80%.

So I modified the code like so:

n = 0
while True:
  n += 1
  if n > 1:
    print 'to sleep'
    time.sleep(100000000)
    continue
  job1()
  job2()

I find the CPU consumption is 80% when it in sleep(). Why did it happen?

Marcello B.
  • 4,177
  • 11
  • 45
  • 65
makicn
  • 43
  • 5
  • 1
    I don't understand your second bit of code. It seems like it will run the jobs once, then on every subsequent loop it will sleep then `continue` which skips the jobs, and sleep again, never doing any useful work. And the `sleep` duration is three years?! – John Zwinck Jan 07 '15 at 02:40
  • @JohnZwinck I'm guessing the OP figured that should be long enough to figure out why the CPU stays pretty high. – Wayne Werner Jan 07 '15 at 02:44
  • I want to check the CPU consumption not down even it in sleep() – makicn Jan 07 '15 at 02:45
  • 1
    Maybe `job2()` never returns? You could put some print statements in to check this. But certainly `time.sleep()` is not eating your CPU cycles. – John Zwinck Jan 07 '15 at 02:53
  • I am sure job2 returned. I guess maybe job2 imported some modules, and the modules will eat a lot CPU when the python doing the garbage collections in the background(asyncronism). – makicn Jan 07 '15 at 03:31

1 Answers1

0

The sleep() function suspends execution of the process, which means that the process scheduler can schedule other jobs for execution on the CPU. This could explain the high usage percentage, especially if you have other CPU-hungry tasks running in the background.

It would be helpful to know how you measure the CPU usage.

VHarisop
  • 2,816
  • 1
  • 14
  • 28