Created
November 11, 2015 15:06
-
-
Save carbonin/675f57b620a687bcdd7a to your computer and use it in GitHub Desktop.
Script to test performance of db inserts like rubyrep
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require 'pg' | |
| require 'benchmark' | |
| require 'io/console' | |
| class DbPerf | |
| TEST_DB = 'timing_test_database' | |
| TEST_TABLE = 'timing_test_table' | |
| INSERT_QUERY = "insert into #{TEST_TABLE} (data) values ('#{"a" * 100}')" | |
| def initialize(host, db_user, password) | |
| @host = host | |
| @db_user = db_user | |
| @pass = password | |
| end | |
| def run_test | |
| t = 0 | |
| create_test_db | |
| with_test_conn do |c| | |
| t = Benchmark.realtime do | |
| c.transaction do |trans_conn| | |
| 1000.times { trans_conn.exec(INSERT_QUERY) } | |
| end | |
| end | |
| end | |
| destroy_test_db | |
| # convert to ms | |
| t * 1000 | |
| end | |
| private | |
| def with_pg_conn | |
| conn = PG::Connection.open(:dbname => 'postgres', :host => @host, :user => @db_user, :password => @pass) | |
| yield conn | |
| ensure | |
| conn.close | |
| end | |
| def with_test_conn | |
| conn = PG::Connection.open(:dbname => TEST_DB, :host => @host, :user => @db_user, :password => @pass) | |
| yield conn | |
| ensure | |
| conn.close | |
| end | |
| def create_test_db | |
| with_pg_conn { |c| c.exec("create database #{TEST_DB}") } | |
| with_test_conn { |c| c.exec("create table #{TEST_TABLE} (data varchar)") } | |
| end | |
| def destroy_test_db | |
| with_pg_conn { |c| c.exec("drop database #{TEST_DB}") } | |
| end | |
| end | |
| remote_host = ARGV[0] | |
| user = ARGV[1] | |
| puts "Enter the password for #{user}@#{remote_host}" | |
| pass = STDIN.noecho(&:gets).strip | |
| test = DbPerf.new(remote_host, user, pass) | |
| time = 0 | |
| 10.times { time += test.run_test } | |
| puts "Test insert ran in %.6f ms on average" % (time / 10) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment