Setting CPU Affinity in Ruby


/ Published in: Ruby
Save to your folder(s)



Copy this code and paste it in your HTML
  1. require 'rubygems'
  2. require 'inline'
  3.  
  4. # By Peter Cooper - http://www.rubyinside.com/
  5. # Oodles of inspiration and examples from
  6. # http://www-128.ibm.com/developerworks/linux/library/l-affinity.html
  7.  
  8. class LinuxScheduler
  9. inline do |builder|
  10. builder.include '<sched.h>'
  11. builder.include '<stdio.h>'
  12. builder.c '
  13. int _set_affinity(int cpu_id) {
  14. cpu_set_t mask;
  15. __CPU_ZERO(&mask);
  16. __CPU_SET(cpu_id, &mask);
  17. if(sched_setaffinity(getpid(), sizeof(mask), &mask ) == -1) {
  18. printf("WARNING: Could not set CPU Affinity, continuing as-is\n");
  19. return 0;
  20. }
  21. return 1;
  22. }
  23. '
  24. end
  25.  
  26. # cpu_id is 0-based, so for core/cpu 1 = 0, etc..
  27. def self.set_affinity(cpu_id)
  28. self.new._set_affinity(cpu_id.to_i)
  29. end
  30. end
  31.  
  32.  
  33. # Set this process's CPU affinity
  34. LinuxScheduler.set_affinity(ARGV.first)
  35.  
  36. # Hog up all the CPU time on that processor
  37. 1000000.times { b = rand(100) ** 100 }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.