How can I speed up Ruby/Rake task

2019-02-21 19:38发布

问题:

rake --tasks takes about 18s to run. This is just the time it takes to load all the tasks, as a result any task I define will take at least this amount of time to run :

$time rake --tasks
rake db:clean           # Cleaning up database
rake passenger:restart  # Restart Application
rake spec               # Run specs

real    0m18.816s
user    0m7.306s
sys 0m5.665s

My Rakefile :

$: << "."
require "rubygems"
require "rspec/core/rake_task"

desc "Run those specs"
task :spec do
  RSpec::Core::RakeTask.new(:spec) do |t|
    t.rspec_opts = %w{--colour --format progress}
    t.pattern = 'spec/*_spec.rb'
  end
end

task :default  => :spec

Any idea why rake takes to much times ? Thanks

回答1:

Try spring

Command line will look like:

spring rake -T

It will take more time running the first time, but subsequent runs will be very fast.



回答2:

This solution worked for me: Faster rake tasks in Rails.

I had to do a little variation where I created a lib/tasks/no_rails directory and put all the Rake files which do not need Rails in there and loaded only those using the above method.



回答3:

I like the solution Pratik mentions for the general case of loading rails for tasks that need it and not for those that don't, for any rake task without having to remember beforehand.

A less-invasive method to run a rake task that doesn't need rails is to use the -f rake option to tell rake to use a particular Rakefile. This way, rake won't go looking for rake tasks in all of rails.

For example, assuming your task above is in a file called Rakefile at the top level of your project and your Rakefile doesn't do anything that loads Rails like require File.expand_path('../config/application', __FILE__), you can do:

$ rake -f Rakefile spec

and it should run your spec task much faster. Try $ time rake -f Rakefile -T; I did this with a rails-independent Rakefile of mine and got:

real    0m1.543s
user    0m1.308s
sys     0m0.201s

The downside is you have to remember to specify this option every time, and not to specify it if you want to run a rake task from rails like rake db:migrate.



回答4:

The entire rails environment has to be loaded, therefore even simple rake tasks such as rake --tasks take a while. Opening a console with rails console or script/console takes a similar time. You may try to hack Ruby or Rails to speed up rake, but too much optimization can be bad if you want to switch to a newer version later. Since the rails environment must be loaded, cleaning up routes may also help.