mardi 5 décembre 2017

multi thread slower than single tread in ruby

I am trying to benchmark the below code,

the method Rate.rate_by_service, does some DB calls / processing and returns a value

mutex = Mutex.new
thread_arr = []
puts Benchmark.measure{
1000.times do |i|
  services.each_with_index do |service_obj,index|
    thread_arr[index] = Thread.new {
      mutex.synchronize {
        rate << Rate.rate_by_service(service_obj,@package,@from,@to,@credentials) #does database calls / calcualtions and returns a value
      }
    }
    #rate << 
  end
  thread_arr.each {|t| t.join}
end
}

The strange thing i have observed is that the multi threaded version is slower that the regular version(without threads)

Here are the benchmarking results.

 #threading
 4.870000   0.490000   5.360000 (  6.846712)
 5.300000   0.520000   5.820000 (  7.550946)
 4.640000   0.480000   5.120000 (  6.720078)
 4.580000   0.460000   5.040000 (  6.344415)
 4.510000   0.450000   4.960000 (  6.312238)




#no threading
3.610000   0.240000   3.850000 (  4.088772)
3.360000   0.200000   3.560000 (  3.721254)
3.380000   0.190000   3.570000 (  3.795252)
3.500000   0.200000   3.700000 (  4.156553)
3.580000   0.210000   3.790000 (  4.183601)

is there something wrong that I am doing? Can anyone please elaborate as to why this behaviour could be happening.

I am using ruby 2.0, rails Rails 4.2.7.1

Aucun commentaire:

Enregistrer un commentaire