Skip to content

Instantly share code, notes, and snippets.

@aroben
Last active November 7, 2016 16:26
Show Gist options
  • Save aroben/61f30ebd50bfb86d72cd29a1c00a7eba to your computer and use it in GitHub Desktop.
Save aroben/61f30ebd50bfb86d72cd29a1c00a7eba to your computer and use it in GitHub Desktop.
sketch of a ProcessUtilization rework
class ProcessStats
include Singleton
def add_source(source)
@sources << source
end
def snapshot
Snapshot.new(@sources)
end
def measure
before = snapshot
yield
snapshot - before
end
class Snapshot
attr_reader :data
def initialize(sources)
@data = sources.each_with_object({}) { |source, hash|
hash.update(source.sample)
}.freeze
end
def -(other)
(data.keys | other.keys).each_with_object({}) { |key, hash|
hash[key] = data.fetch(key, 0) - other.fetch(key, 0)
}.freeze
end
end
end
class ProcessClockStatsSource
def sample
times = Process.times
cpu = times.utime + times.stime
{
:cpu_time => cpu,
:real_time => times.real,
:idle_time => times.real - cpu,
}.freeze
end
ProcessStats.instance.add_source(self.new)
end
class ProcessUtilization
def call(env)
result = nil
diff = ProcessStats.instance.measure {
result = @app.call(env)
}
record_request(diff)
result
end
private
def record_request(snapshot_diff)
snapshot_diff.each do |key, value|
stats.histogram("request.#{key}", value)
end
end
end
class GraphQL
def execute(query)
result = nil
diff = ProcessStats.instance.measure {
result = inner_execute(query)
}
# save diff somewhere for later (e.g., rendering in a performance dump)
result
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment