Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Fast way to profile a Ruby program
# In your code, right at the top of any source code file.
trap 'PROF' do
File.open("/tmp/profile-#{Time.current.to_f}", 'w') {|f| f.write caller(2).join("\n") }
pid = $$
Thread.new { sleep 0.5; `kill -PROF #{pid}` }
end
# in a terminal
while true; do
sleep 0.1
kill -PROF {pid_of_your_code_running}
done
# In an irb session:
profile = Dir["/tmp/profile*"].map {|f| File.read(f).lines.first.split(/:in/).first }.reduce(Hash.new {|h,k| h[k] = 0 }) {|h, line| h[line] = h[line] + 1; h }.sort_by(&:last)
@JackDanger

This comment has been minimized.

Copy link
Owner Author

@JackDanger JackDanger commented Aug 2, 2016

Or to analyze memory usage:

ObjectSpace.each_object.reduce(Hash.new {|h,k| h[k] = 0 }) {|all, object| all[object.class] += 1; all }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment