Advertisement
v_ignatyev

Benchmarking: comparing MongoDb vs Redis performance

Jan 15th, 2013
154
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.40 KB | None | 0 0
  1. #
  2. # Comparing Redis & MongoDb performance
  3. #
  4. # Benchmarking cache read/write ops
  5. #
  6. # See explanation at: http://joydevel.blogspot.ru/2011/03/mongodb-mongodb-vs-redis.html
  7.  
  8.  
  9. #!/usr/bin/env python2.7
  10. import sys, time
  11. from pymongo import Connection
  12. import redis
  13.  
  14. # connect to redis & mongodb
  15. redis = redis.Redis()
  16. mongo = Connection().test
  17. collection = mongo['test']
  18. collection.ensure_index('key', unique=True)
  19.  
  20. def mongo_set(data):
  21.     for k, v in data.iteritems():
  22.         collection.insert({'key': k, 'value': v})
  23.  
  24. def mongo_get(data):
  25.     for k in data.iterkeys():
  26.         val = collection.find_one({'key': k}, fields=('value',)).get('value')
  27.  
  28. def redis_set(data):
  29.     for k, v in data.iteritems():
  30.         redis.set(k, v)
  31.  
  32. def redis_get(data):
  33.     for k in data.iterkeys():
  34.         val = redis.get(k)
  35.  
  36. def do_tests(num, tests):
  37.     # setup dict with key/values to retrieve
  38.     data = {'key' + str(i): 'val' + str(i)*100 for i in range(num)}
  39.     # run tests
  40.     for test in tests:
  41.         start = time.time()
  42.         test(data)
  43.         elapsed = time.time() - start
  44.         print "Completed %s: %d ops in %.2f seconds : %.1f ops/sec" % (test.__name__, num, elapsed, num / elapsed)
  45.  
  46. if __name__ == '__main__':
  47.     num = 1000 if len(sys.argv) == 1 else int(sys.argv[1])
  48.     tests = [mongo_set, mongo_get, redis_set, redis_get] # order of tests is significant here!
  49.     do_tests(num, tests)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement