Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Set CPU Affinity For A Ruby Script In Linux

DZone's Guide to

Set CPU Affinity For A Ruby Script In Linux

·
Free Resource
require 'rubygems'
require 'inline'

# Oodles of inspiration and examples from
# http://www-128.ibm.com/developerworks/linux/library/l-affinity.html

class LinuxScheduler
  inline do |builder|
    builder.include '
  
   '
    builder.include '
   
    '
    builder.c '
      int _set_affinity(int cpu_id) {
        cpu_set_t mask;
        __CPU_ZERO(&mask);
        __CPU_SET(cpu_id, &mask);
        if(sched_setaffinity(getpid(), sizeof(mask), &mask ) == -1) {
          printf("WARNING: Could not set CPU Affinity, continuing as-is\n");
          return 0;
        }
        return 1;
      }
    '
  end

  # cpu_id is 0-based, so for core/cpu 1 = 0, etc..
  def self.set_affinity(cpu_id)
    self.new._set_affinity(cpu_id.to_i)
  end
end


# Set this process's CPU affinity
LinuxScheduler.set_affinity(ARGV.first)

# Hog up all the CPU time on that processor
1000000.times { b = rand(100) ** 100 }
   
  
Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}