日期:2014-05-16 浏览次数:20541 次
> db.blog.findOne() { _id: 1, title: "No Free Lunch", author: "Alex", comments: [ { who: "John", comment: "I agree" }, { who: "Felix", comment: "You must be joking..." }, ] }
from pymongo import Connection import sys, time # 目的:测试Mongo中内嵌文档的插入速度 conn = Connection() db = conn.bench conn.drop_database('bench') def insert_embbded_comments(n, comment_len, count=1, safe=False): comment_text = 'a'*comment_len start = time.time() for c in xrange(count): blog = {'_id': c, 'title': 'Mongodb Benchmark'} db.blog.insert(blog) for i in xrange(n): db.blog.update({'_id': c}, {'$push': { 'comments': {'comment': comment_text}}}, safe=safe) end = time.time() return end - start def insert_comments(n, comment_len, count=1, safe=False): comment_text = 'a'*comment_len start = time.time() for c in xrange(count): for i in xrange(n): db.blog.comments.insert({'comment': comment_text}, safe=safe) end = time.time() return end - start def bench(safe=False): total = 10000 print '===== %sINSERT %s comments =====' % ('SAFE ' if safe else '', total) print '%12s %15s %15s %15s %15s %15s' % ('', '1(x10000)', '10(x1000)', '100(x100)', '1000(x10)', '10000(x1)') sys.stdout.write('%12s ' % 'Embeded') sys.stdout.flush() row_types = (1, 10, 100, 1000, 10000) for nrows in row_types: conn.drop_database('bench') count = total / nrows time = insert_embbded_comments(nrows, 1000, count=count, safe=safe) sys.stdout.write('%15s%s' % (time, '\n' if nrows==row_types[-1] else ' ')) sys.stdout.flush() sys.stdout.write('%12s ' % 'Non-embeded') for nrows in row_types: count = total / nrows conn.drop_database('bench') time = insert_comments(nrows, 1000, count=count, safe=safe) sys.stdout.write('%15s%s' % (time, '\n' if nrows==row_types[-1] else ' ')) sys.stdout.flush() bench() bench(safe=True)
===== INSERT 10000 comments ===== 1(x10000) 10(x1000) 100(x100) 1000(x10) 10000(x1) Embeded 2.31141519547 1.42457890511 1.34223604202 4.3767850399 35.7308151722 Non-embeded 1.29936504364 1.30167293549 1.30044412613 1.29023313522 1.29240202904 ===== SAFE INSERT 10000 comments ===== 1(x10000) 10(x1000) 100(x100) 1000(x10) 10000(x1) Embeded 5.45804405212 4.29802298546 4.95570802689 13.7657668591 107.089906216 Non-embeded 3.68912506104 3.65784692764 3.77990913391 3.66531991959 3.70736408234