tags:

views:

533

answers:

4

I already found a solution for "Most unixes" via cmdline "cat /proc/cpuinfo", but a pure-ruby solution would be nicer...

+5  A: 

Surely if you can cat it, you can open, read and close it using the standard features of the language without resorting to a system()-type call.

You may just need to detect what platform you're on dynamically and either:

  • use the /proc/cpuinfo "file" for Linux; or
  • communicate with WMI for Windows.

That last line can use:

require 'win32ole'
wmi = WIN32OLE.connect("winmgmts://")
info = wmi.ExecQuery ("select * from Win32_ComputerSystem")

Then use info's NumberOfProcessors item.

paxdiablo
Or possibly NumberOfProcessors. ;-)
Stobor
Thanks, I hoped it would be something easy, for now I will skip this feature :)
grosser
Thanks, @Stobor, fixed.
paxdiablo
+5  A: 

with JRuby you can check it with the following Java code:

 Runtime runtime = Runtime.getRuntime();   
 int numberOfProcessors = runtime.availableProcessors();
dfa
I've voted this one up particularly because of the implicit point that with JRuby you can actually use those extra cores with Ruby's Thread class! Might it be worth adding this version of the example too?#!/usr/bin/jrubyinclude Javaputs "You have #{java.lang.Runtime.getRuntime.availableProcessors} cores"
Mark Longair
+6  A: 
$ gem install facter
$ irb
irb(main):001:0> require 'rubygems'
=> true
irb(main):002:0> require 'facter'
=> true
irb(main):003:0> Facter.loadfacts
=> true
irb(main):004:0> puts Facter.sp_number_processors
2
=> nil
irb(main):005:0>

This facter gem is the best, it's not platform specific and designed to do this exact thing.

Anko
nice solution, ill check it out, since i am working on a public library i did not want to add an extra dependency for something this trivial
grosser
+1  A: 

on Mac:

thiago-pradis-macbook:~ tchandy$ hwprefs cpu_count

2