X-Git-Url: http://jaekl.net/gitweb/?p=quanlib.git;a=blobdiff_plain;f=tconn.rb;fp=tconn.rb;h=43fa0f5c5cda97e7d83e42e401ba5ebd78935ed5;hp=0000000000000000000000000000000000000000;hb=872d620121706ad345b7e667521be1c7326c2e00;hpb=952e15e8397db7ca1aad1f71e66f529b31cb75ce diff --git a/tconn.rb b/tconn.rb new file mode 100644 index 0000000..43fa0f5 --- /dev/null +++ b/tconn.rb @@ -0,0 +1,71 @@ +# tconn.rb +# +# Timed Connection: +# Wrapper around a PG Connection that provides a report on where time was spent executing SQL +# + +require 'pg' + +class TimedConn + def initialize(wrapped_conn) + @conn = wrapped_conn + @stmts = {} + @total_time = 0 + end + + def close + @conn.close() + puts "Connection closing. Total SQL time: " + @total_time.to_s + " secs" + @stmts.each do |sql, info| + elapsed = info[2] + calls = info[1] + puts elapsed.to_s + " secs: " + calls.to_s + " times: " + sql + end + end + + def exec(*args, &block) + before = Time.now + #puts args.inspect + result = @conn.exec(*args) + #puts result.inspect + after = Time.now + elapsed = (after - before) + remember(args[0], elapsed) + @total_time += elapsed + if block_given? + yield(result) + else + return result + end + end + + def exec_params(*args, &block) + before = Time.now + #puts args.inspect + result = @conn.exec_params(*args) + #puts result.inspect + after = Time.now + elapsed = (after - before) + remember(args[0], elapsed) + @total_time += elapsed + if block_given? + yield(result) + else + return result + end + end + + def remember(sql, elapsed) + if @stmts.has_key?(sql) + stmt = @stmts[sql] + else + stmt = [sql, 0, 0] + end + + stmt[1] += 1 # Number of times this statement has been invoked + stmt[2] += elapsed # total elapsed time spent on this statement + + @stmts[sql] = stmt + end +end +