Skip to content

Instantly share code, notes, and snippets.

@andrehjr
Created January 12, 2024 12:28
Show Gist options
  • Save andrehjr/fffb2cf515c8bad99f394b842c32f70a to your computer and use it in GitHub Desktop.
Save andrehjr/fffb2cf515c8bad99f394b842c32f70a to your computer and use it in GitHub Desktop.
Top slowest factories
def red(text)
"\033[31m#{text}\033[0m"
end
load_begin = Time.now
# This will return slowest factories within the suite
stats = {}
ActiveSupport::Notifications.subscribe("factory_bot.run_factory") do |_name, start, finish, _id, payload|
execution_time_in_seconds = finish - start
stats[payload[:name]] = stats[payload[:name]].to_f + execution_time_in_seconds
end
RSpec.configure do |config|
config.after(:suite) do
sorted_stats = stats.sort_by { |_name, execution_time| -execution_time }.take(10)
slowest_sum = sorted_stats.inject(0) { |sum, stat| sum + stat.last }
total_time = Time.now - load_begin
$stdout.puts "\nTop 10 slowest factories (#{slowest_sum.round(2)} seconds, #{(slowest_sum / total_time * 100).round(2)}% of total time):"
sorted_stats.each do |name, execution_time|
$stdout.puts " #{red("#{execution_time.round(5)} seconds")} - #{name}"
end
end
end
#######
# Top 10 slowest factories (205.04 seconds, 15.16% of total time):
# 31.30768 seconds - confirmed_user_with_account
# 24.99767 seconds - confirmed_user_with_account_xxx
# 23.36607 seconds - xxxxx
# 23.17119 seconds - xxxxx
# 20.36791 seconds - xxxxx
# 19.93632 seconds - xxxxx
# 16.45433 seconds - xxxxx
# 16.00099 seconds - xxxxx
# 14.78478 seconds - xxxxx
# 14.65802 seconds - account_sequence
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment