Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

James Robertson http://www.r0bertson.co.uk

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Ruby Threading

Uses Ruby (version 1.8) threading to run code in parallel which reduces the time taken for the script to complete.
   1  
   2  require 'ping' #from core classes
   3  @ip_prefix='192.168.1.'
   4  
   5  def ping_ip(i)
   6    puts "Found #{@ip_prefix + i.to_s}" if Ping.pingecho(@ip_prefix+i.to_s,1)
   7  end
   8  
   9  p50 = Thread.new{(1..50).each{|i| ping_ip(i) };puts 'p50-finished'}
  10  p100 = Thread.new{(51..100).each{|i| ping_ip(i) };puts 'p100-finished'}
  11  p150 = Thread.new{(101..150).each{|i| ping_ip(i) }; puts 'p150-finished'}
  12  p200 = Thread.new{(151..200).each{|i| ping_ip(i) }; puts 'p200-finished'}
  13  p254 = Thread.new{(201..254).each{|i| ping_ip(i) }; puts 'p254-finished'}

output:
   1  
   2  Found 192.168.1.2
   3  Found 192.168.1.3
   4  Found 192.168.1.8
   5  Found 192.168.1.9
   6  Found 192.168.1.10
   7  Found 192.168.1.11
   8  Found 192.168.1.12
   9  Found 192.168.1.13
  10  Found 192.168.1.15
  11  Found 192.168.1.110
  12  Found 192.168.1.21
  13  Found 192.168.1.22
  14  Found 192.168.1.140
  15  p50-finished
  16  p150-finished
  17  Found 192.168.1.200
  18  p200-finished
  19  p100-finished
  20  Found 192.168.1.254
  21  p254-finished

This script took about 1 minute to complete, whereas the non-threaded script took around 4 minutes to complete.

Reference: Ruby Threads: RUBY THREADS [rubylearning.com]

*update 11:21pm*
I tried the same experiment again this time with 26 threads (9 pings each on average) and the script finished in under 15 seconds.

*update 11:39pm*
A separate thread for each ping seems to work best, since it only took a couple of seconds to finish.
   1  
   2  (1..254).each{|i| Thread.new {puts 'Found ' + ip_prefix + i.to_s if Ping.pingecho(ip_prefix+i.to_s,10)}}

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS