Ruby SQLite3 Activerecord太慢

Ruby SQLite3 Activerecord太慢,ruby,performance,activerecord,sqlite,Ruby,Performance,Activerecord,Sqlite,我一直在为sqlite使用activerecord适配器(没有rails),当我尝试插入任何东西时,它似乎太慢了。例如,当我插入约250次时,很容易需要5分钟以上!我的模式如下所示: create_table :courses do |t| t.string :title t.integer :ethmmy_id end add_index :courses, :ethmmy_id create_table :announcements do |t| t.string

我一直在为sqlite使用activerecord适配器(没有rails),当我尝试插入任何东西时,它似乎太慢了。例如,当我插入约250次时,很容易需要5分钟以上!我的模式如下所示:

create_table :courses do |t|
    t.string :title
    t.integer :ethmmy_id
end

add_index :courses, :ethmmy_id

create_table :announcements do |t|
    t.string :title
    t.string :author
    t.string :body
    t.string :uhash
    t.belongs_to :courses
    t.timestamps null: false
end

add_index :announcements, :courses_id
class Course < ActiveRecord::Base
    validates :ethmmy_id, uniqueness: true
    has_many :announcements
end

class Announcement < ActiveRecord::Base
    validates :uhash, uniqueness: true
    belongs_to :course
end
我使用的ActiveRecord模型如下所示:

create_table :courses do |t|
    t.string :title
    t.integer :ethmmy_id
end

add_index :courses, :ethmmy_id

create_table :announcements do |t|
    t.string :title
    t.string :author
    t.string :body
    t.string :uhash
    t.belongs_to :courses
    t.timestamps null: false
end

add_index :announcements, :courses_id
class Course < ActiveRecord::Base
    validates :ethmmy_id, uniqueness: true
    has_many :announcements
end

class Announcement < ActiveRecord::Base
    validates :uhash, uniqueness: true
    belongs_to :course
end
但仍然没有性能提升

为了测试,我甚至试着把整个数据库放进更多的内存中,而整个过程仍然只花了大约5分钟就完成了250个插入。调试日志显示,SQL查询每次仅为0.1-0.2毫秒,在某些插入(每次都是相同的插入)时,整个过程似乎在那里冻结了几秒钟


更新:在使用ruby prof查找大部分时间花在哪里之后,我发现80%以上的时间都花在IO.select上。这个方法是什么?是什么调用它的?

您是否考虑过改为mysql而不是sqlite

无论如何,使插入更快的一种方法是在原始sql中而不是通过activerecord进行插入。每次调用create时,几乎有10个回调被触发,诸如此类

创建一个sql查询以插入一整组数据可以如下所示:

ActiveRecord::Base.transaction do
    Course.all.each do |course|
         Announcement.create(....)
    end
end
base_sql = 'INSERT INTO announcements (`title`, `author`, `body`, `uhash`, `course_id`) VALUES '
announcements = []
Course.all.each do |course|
  announcements << [title, author, body, uhash, course.id]
end

values_sql = announcements.map { |announcement| "(#{announcement.join(', ')})" }.join(', ')
ActiveRecord::Base.connection.execute(base_sql + values_sql)
base\u sql='插入公告(`title`、`author`、`body`、`uhash`、`course\u id`)值'
公告=[]
各就各位,各就各位|

关于这个主题的进一步阅读公告:我想继续使用activerecord,因为它非常方便。所以我想我可以尝试一个合适的数据库管理系统。我已经读过那篇文章并尝试了一些建议,但毫无收获的是,你的插入中有什么瓶颈?在数据库和activerecord中花费了多少时间?您是否正在运行本地环境?我通常查看我的日志/development.log。如果这通常是在某种rake任务中完成的,我想还有其他分析器。或者,为了调试的目的,您可以将其移动到任何路由。