Skip to content

Commit

Permalink
Feat: Support JSON output to STDOUT (#125)
Browse files Browse the repository at this point in the history
I want to support `benchmark-ips` in
github-action-benchmark.
https://github.com/benchmark-action/github-action-benchmark

When it can write the result to STDOUT in JSON format, it would
be easy to support it.
This commits changes JSON output so that it can directly write
to a given argument if it responds to `write`.
It also adds tests and a section about JSON in README.
  • Loading branch information
okuramasafumi authored Feb 14, 2023
1 parent ea645f6 commit 9f2bbda
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 3 deletions.
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,29 @@ Benchmark.ips do |x|
end
```

### Output as JSON

You can generate output in JSON. If you want to write JSON to a file, pass filename to `json!` method:

```ruby
Benchmark.ips do |x|
x.report("some report") { }
x.json! 'filename.json'
end
```

If you want to write JSON to STDOUT, pass `STDOUT` to `json!` method and set `quiet = true` before `json!`:

```ruby
Benchmark.ips do |x|
x.report("some report") { }
x.quiet = true
x.json! STDOUT
end
```

This is useful when the output from `benchmark-ips` becomes an input of other tools via stdin.

## REQUIREMENTS:

* None!
Expand Down
10 changes: 7 additions & 3 deletions lib/benchmark/ips/report.rb
Original file line number Diff line number Diff line change
Expand Up @@ -183,9 +183,13 @@ def run_comparison(order)
# Generate json from Report#data to given path.
# @param path [String] path to generate json.
def generate_json(path)
File.open path, "w" do |f|
require "json"
f.write JSON.pretty_generate(data)
require "json"
if path.respond_to?(:write) # STDOUT
path.write JSON.pretty_generate(data)
else
File.open path, "w" do |f|
f.write JSON.pretty_generate(data)
end
end
end
end
Expand Down
17 changes: 17 additions & 0 deletions test/test_benchmark_ips.rb
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,23 @@ def test_json_output
assert data[0]["stddev"]
end

def test_json_output_to_stdout
Benchmark.ips do |x|
x.report("sleep 0.25") { sleep(0.25) }
x.quiet = true
x.json! $stdout
end

assert $stdout.string.size > 0

data = JSON.parse $stdout.string
assert data
assert_equal 1, data.size
assert_equal "sleep 0.25", data[0]["name"]
assert data[0]["ips"]
assert data[0]["stddev"]
end

def test_hold!
temp_file_name = Dir::Tmpname.create(["benchmark-ips", ".tmp"]) { }

Expand Down

0 comments on commit 9f2bbda

Please sign in to comment.