【发布时间】:2015-05-12 13:02:25
【问题描述】:
我一直在为 sqlite 使用 activerecord 适配器(没有导轨),当我尝试插入任何东西时,它似乎太慢了。例如,当我进行约 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
我使用的 ActiveRecord 模型如下:
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
我尝试修改 PRAGMAS,例如在内存中设置日志或关闭同步 I/O,但似乎没有太大区别。数据是从网络爬虫中获取的,但这不是瓶颈,因为爬虫本身非常快。
更具体地说,我注意到它每 10 次左右的插入就会冻结一次以写入数据库,但它似乎很慢。我尝试将这些创作添加到这样的单个事务中:
ActiveRecord::Base.transaction do
Course.all.each do |course|
Announcement.create(....)
end
end
但仍然没有性能提升。
为了测试,我什至尝试增加整个数据库,而整个过程仍然需要大约 5 分钟才能插入 250 次。调试日志显示每个 SQL 查询只有大约 0.1-0.2 毫秒,并且在某些插入(每次相同的插入)处,整个事情似乎冻结了几秒钟。
更新:在使用 ruby-prof 找到大部分时间都花在了哪里之后,我发现 80% 甚至更多的时间都花在了 IO.select 上。这个方法是什么,叫什么?
【问题讨论】:
标签: ruby performance activerecord sqlite