最近用到批量生成大量数据,为避免客户端产生假死的状态,因此测试了以下几种方式的效率

def test1
  params=[]
  puts Time.now
  10000.times do |i|
    e_quiz = ExaminationQuiz.new
    e_quiz.examination_id = 1
    e_quiz.quiz_id = i
    params.push(e_quiz)
  end
  puts Time.now
  ExaminationQuiz.create(params)
  puts Time.now
end
def test2
  params=[]
  s = Examination.first
  puts Time.now
  10000.times do |i|
    
    s.examination_quizzes.create(:quiz_id=>i) 
    end
  puts Time.now
end

 

def test3
  params=[]
 con = ActiveRecord::Base.connection()
  puts Time.now
  10000.times do |i|
    params.push("('title',6,1,1,'',1,'','true',1,1,'#{Time.now.to_s(:db)}','#{Time.now.to_s(:db)}')")
  end
  sql = "INSERT INTO examination_quizzes (title,user_id,examination_id,quiz_id,quiz_type,submit_answer_id,submit_answer_name,is_correct,level_id,position,created_at,updated_at)VALUES #{params.join(", ")}"
  puts Time.now
  con.insert sql
  puts Time.now
end

  

 

  测试结果如下:

ruby-1.9.2-p180 :118 >   test1
Tue, 23 Oct 2012 16:35:42 +0800
Tue, 23 Oct 2012 16:35:43 +0800
Tue, 23 Oct 2012 16:36:06 +0800
 => nil 
ruby-1.9.2-p180 :119 > test3
Tue, 23 Oct 2012 16:36:11 +0800
Tue, 23 Oct 2012 16:36:13 +0800
Tue, 23 Oct 2012 16:36:13 +0800
 => nil 
ruby-1.9.2-p180 :120 > test2
Tue, 23 Oct 2012 16:36:54 +0800
Tue, 23 Oct 2012 16:39:04 +0800
 => nil 

  有结果可以看出,使用sql批量创建数据的速度最快!

posted on 2012-10-23 16:48  yanmiao  阅读(639)  评论(0编辑  收藏  举报