Quiz: which ruby program uses more CPU?

Program A:

sleep(100)

Program B:

t = Thread.new do
  sleep(100)
end

t.join

Which program uses more CPU? Hint: this is ruby 1.8.6.

The simple test

Run both programs overnight (surround the sleep(100) with a repeating while), and ‘ps aux’ to see cpu usage.

The complex test that explains what is happening

Run both programs with valgrind / kcachegrind, or pop into gdb.

The answer

Now, neither of these programs use a lot of CPU, but if you leave them running for long periods of time, one program will continue to use CPU cycles and the other will not. While they should both be blocking for 100 seconds, one is waking up every 10ms. Why?

By default ruby creates one operating system thread that runs your ruby code. If you create one or more threads, however, ruby creates a second operating system thread. This second thread wakes up every 10ms, checks to see if it trapped an interrupt signal, checks to see if the thread was canceled, and then goes back to sleep. You can verify this by popping into gdb and looking at where your threads are. This second thread, while not using very much CPU, does use some. Hence, Program B uses more CPU.

Morals

Don’t use threads if you don’t have to, but *really* don’t worry too much about it. If you’re that short on CPU cycles, you should probably be getting some more hardware.

Tagged . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

One Trackback

  1. [...] Quiz: which ruby program uses more CPU? [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>