Skip to content

Instantly share code, notes, and snippets.

@IlkhamGaysin
Last active August 10, 2017 14:44
Show Gist options
  • Save IlkhamGaysin/ef9de975c044c8bb2df8add6811f8f98 to your computer and use it in GitHub Desktop.
Save IlkhamGaysin/ef9de975c044c8bb2df8add6811f8f98 to your computer and use it in GitHub Desktop.
Simple benchmarking memory usage and spend time

Simple benchmarking memory usage and spend time

Usage

print_metrics do
  #...your code...#
end

# Or by single method

print_memory_usage do
  #...your code...#
end

print_time_spent do
  #...your code...#
end
require 'benchmark'

def print_metrics
  print_memory_usage do
    print_time_spent do
      yield
    end
  end
end

def print_memory_usage
  memory_before = `ps -o rss= -p #{Process.pid}`.to_i
  
  yield
  
  memory_after = `ps -o rss= -p #{Process.pid}`.to_i

  puts "Memory: #{((memory_after - memory_before) / 1024.0).round(2)} MB"
end

def print_time_spent
  time = Benchmark.realtime do
    yield
  end

  puts "Time: #{time.round(2)}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment