Skip to content

Instantly share code, notes, and snippets.

@JackDanger
Last active August 2, 2016 18:05
Show Gist options
  • Save JackDanger/1733659461861e55e4d9 to your computer and use it in GitHub Desktop.
Save JackDanger/1733659461861e55e4d9 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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