Benchmarking Faster Updates

A simple benchmark utility for comparing the performance of three write strategies for MongoDB 2.4.

require 'mongo'  
require 'benchmark'

@mongo_client = Mongo::MongoClient.from_uri(ENV["MONGOHQ_URL"], { w:2 })

@db = @mongo_client['test']
@collection = @db['benchtest']

@counts = 1000

def resetdb()  
  if @collection.count > 0
    @collection.remove()
  end

  docarray=[]

  for i in 1..@counts do
    newdoc= { "myid" => i, "name" => "bar#{i}" }
    docarray << newdoc
  end

  @collection.insert(docarray)
end

Benchmark.bm do |x|  
  resetdb
  x.report("w=0") {
    for i in 1..@counts do
      @collection.update({ "myid" => i }, { "$set" => { "name" => "foo#{i}" }  }, { :w => 0 } )
    end
    @db.get_last_error( { :w=>2 })
  }
  resetdb
  x.report("w=1") {
    for i in 1..@counts do
      @collection.update({ "myid" => i },{ "$set" => { "name" => "foo#{i}" }  }, { :w => 1 } )
    end
    @db.get_last_error( { :w=>2 })
  }
  resetdb
  x.report("w=2") {
    for i in 1..@counts do
      @collection.update({ "myid" => i },{ "$set" => { "name" => "foo#{i}" }  } )
    end
  }
  resetdb
end