Skip to content

Commit 9a0f8e2

Browse files
vchuravyNHDaly
andcommitted
Add utility macros
Co-authored-by: Nathan Daly <[email protected]>
1 parent 1f56c43 commit 9a0f8e2

File tree

2 files changed

+48
-12
lines changed

2 files changed

+48
-12
lines changed

src/LinuxPerf.jl

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,31 @@ module LinuxPerf
22

33
using Printf
44

5+
export @measure, @measured
56
export make_bench, enable!, disable!, reset!, reasonable_defaults, counters
67

78
import Base: show, length, close
89

9-
const SYS_perf_event_open = 298
10+
macro measure(expr, args...)
11+
esc(quote
12+
local bench
13+
_, bench = $LinuxPerf.@measured($expr, $(args...))
14+
$counters(bench)
15+
end)
16+
end
17+
macro measured(expr, events = reasonable_defaults)
18+
quote
19+
local bench = $make_bench($events);
20+
local v
21+
try
22+
$enable!(bench)
23+
v = $(esc(expr))
24+
finally
25+
$disable!(bench)
26+
end
27+
(v, bench)
28+
end
29+
end
1030

1131
mutable struct perf_event_attr
1232
typ::UInt32

test/runtests.jl

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,34 @@ using LinuxPerf
22
using Test
33

44
import LinuxPerf: make_bench, enable!, disable!, reset!, reasonable_defaults, counters
5-
const bench = make_bench(reasonable_defaults);
6-
@noinline function g(a)
7-
enable!(bench)
8-
c = 0
9-
for x in a
10-
if x > 0
11-
c += 1
5+
6+
@testset "simple benchmark" begin
7+
@test begin
8+
bench = make_bench(reasonable_defaults);
9+
@noinline function g(a)
10+
enable!(bench)
11+
c = 0
12+
for x in a
13+
if x > 0
14+
c += 1
15+
end
16+
end
17+
disable!(bench)
18+
c
1219
end
20+
g(zeros(10000))
21+
22+
counters(bench)
23+
24+
true # Succeeded without any exceptions...
1325
end
14-
disable!(bench)
15-
c
1626
end
17-
g(zeros(10000))
1827

19-
counters(bench)
28+
29+
@testset "@measure" begin
30+
c1 = @measure 2 + 2
31+
v, b1 = @measured 2 + 2
32+
33+
@test v === 4
34+
@test typeof(c1) == typeof(counters(b1))
35+
end

0 commit comments

Comments
 (0)