Parsing CacheGrind from Ruby

Posted: January 8, 2010 in Uncategorized

Here’s a little script to show how many times files are accessed during a function call (or integration test) series, for use with tools like XDebug. In my particular application, I had a large codebase and didn’t know what files were touched (or not) during a relatively complex call chain.

require 'optparse'
require 'ostruct'

options = OpenStruct.new()
options.compact = false
OptionParser.new do |opts|
   opts.banner = "Usage: cache_blaser.rb [options]"
   opts.on("-c", "--compact", "Report on directories, not files") do |c|
      options.compact = true
   end
end.parse!

called = {}

ARGV.each do |filename|
   open(filename) do |handle|
      handle.each_line do |line|
          if line=~/^fl=(.*)/
             key = $1
             key = File.dirname(key) if key.include?("/") and options.compact
             called[key] = called.has_key?(key) ? called[key]+1 : 1
          end
      end
   end
end

keys = called.keys.sort do |a,b| 
    (called[b] == called[a]) ? b <=> a : called[b] <=> called[a]
end

keys.each do |file|
    begin 
        printf("%06d | %s\n", called[file], file)
    rescue Errno::EPIPE
    end
end

Usage: (top 50 most accessed files)

ruby cache_blaster.rb /tmp/cachegrind* | head -n 50

The output is number of times something in each file was referenced. This could easily be adapted to also include function calls, or list top function calls for each file.

080976 | php:internal
029876 | /path/to/file/a.php
009454 | /path/to/file/b.php
005875 | /path/to/file/c.php
004552 | /path/to/file/d.php
002433 | /path/to/file/e.php
001522 | /path/to/file/f.php
(etc)

Obviously all this profiling data is already scanned by tools like KCacheGrind, though who really likes GUI tools for more complex data mining and for generating custom reports?

Advertisement

Leave a Reply

Please log in using one of these methods to post your comment:

Gravatar
WordPress.com Logo

Please log in to WordPress.com to post a comment to your blog.

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s