BenchmarkTools macros with Books

Given this example weaved output from a Julia Markdown Document:

image

Generated with this code block:

A = rand(100,100)
B = rand(100,100)
C = rand(100,100)
using BenchmarkTools
function inner_rows!(C,A,B)
  for i in 1:100, j in 1:100
    C[i,j] = A[i,j] + B[i,j]
  end
end
@btime inner_rows!(C,A,B)

How might I achieve the same effect using Books.jl?

So far in my module I have defined a function, inner_rows!:

function inner_rows!(C,A,B)
    for i in 1:100, j in 1:100
        C[i,j] = A[i,j] + B[i,j]
    end
end

Which is called on the page with 3 jl code blocks:

sc("using BenchmarkTools")
s = """
    A = rand(100,100)
    B = rand(100,100)
    C = rand(100,100)
    """
sc(s)
scob("@btime BookTest.inner_rows!(C,A,B) |> string")

Running gen() is successful, but upon serve() the macro output is not shown. Instead only the return value, nothing, is shown.

image

Is there a way to do this in Books.jl?

Note also that I added |> string after trying this code block:

scob("@btime BookTest.inner_rows!(C,A,B)")

Produced the following result. Probably I am going wrong somewhere. This is my first trial run with Books.jl

image

That’s because inner_rows! returns nothing in this case

julia> t = @btime 1 + 1
  0.017 ns (0 allocations: 0 bytes)
2

julia> t
2

One solution is to use @benchmark instead:

But, of course, the real solution is to grab the output from stdout and show that. In a bit of a hacky way, his can be done with IOCapture.jl and # hide comments

```jl
s = """
    A = rand(100,100)
    B = rand(100,100)
    C = rand(100,100)

    function inner_rows!(C,A,B)
      for i in 1:100, j in 1:100
        C[i,j] = A[i,j] + B[i,j]
      end
    end
    c = IOCapture.capture() do # hide
    @btime inner_rows!(C,A,B)
    end # hide
    return c.output # hide
    """
sco(s; post=output_block)
```

which shows on the webpage as:

Another way is to wrap the evaluation step at a later point:

```jl
s = """
    A = rand(100,100)
    B = rand(100,100)
    C = rand(100,100)

    function inner_rows!(C,A,B)
      for i in 1:100, j in 1:100
        C[i,j] = A[i,j] + B[i,j]
      end
    end
    @btime inner_rows!(C,A,B)
    """
c = IOCapture.capture() do
    sc(s)
end
return code_block(s) * "\n\n" * output_block(c.output)
```
1 Like

The problem with the backticks in your post is probably because you didn’t put a newline before and after each code block. That’s a parser problem from Pandoc. I could fix that by always adding a newline before and after each code block, but it seems like a bit of a waste so I didn’t do that (yet).

Yeah, not a big problem.

1 Like

This solution is exactly what I was looking for! Thank you for pointing me in the right direction, and great work on the package!

1 Like