Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use prctl to enable/ disable perf for lower overhead #38

Merged
merged 7 commits into from
Sep 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions src/LinuxPerf.jl
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,20 @@ function Base.show(io::IO, g::EventGroup)
print(io, "\t", g.event_types[end], ")")
end

const SYS_prctl = Clong(157)
const PR_TASK_PERF_EVENTS_DISABLE = Cint(31)
const PR_TASK_PERF_EVENTS_ENABLE = Cint(32)

# syscall is lower overhead than calling libc's prctl
function enable_all!()
res = ccall(:syscall, Cint, (Clong, Clong...), SYS_prctl, PR_TASK_PERF_EVENTS_ENABLE)
Base.systemerror(:prctl, res < 0)
end
function disable_all!()
res = ccall(:syscall, Cint, (Clong, Clong...), SYS_prctl, PR_TASK_PERF_EVENTS_DISABLE)
Base.systemerror(:prctl, res < 0)
end

const PERF_EVENT_IOC_ENABLE = UInt64(0x2400)
const PERF_EVENT_IOC_DISABLE = UInt64(0x2401)
const PERF_EVENT_IOC_RESET = UInt64(0x2403)
Expand Down Expand Up @@ -1064,9 +1078,9 @@ macro pstats(args...)
@debug dump_groups(groups)
bench = make_bench_threaded(groups, threads = $(opts.threads))
try
enable!(bench)
enable_all!()
val = $(esc(expr))
disable!(bench)
disable_all!()
# trick the compiler not to eliminate the code
stats = rand() < 0 ? val : Stats(bench)
return stats::Stats
Expand Down
26 changes: 24 additions & 2 deletions test/runtests.jl
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using LinuxPerf
using Test

using LinuxPerf: make_bench, enable!, disable!, reset!, reasonable_defaults, counters, EventType, EventTypeExt, parse_groups
using LinuxPerf: make_bench, enable!, disable!, reset!, reasonable_defaults, counters, EventType, EventTypeExt, parse_groups, enable_all!, disable_all!

@testset "LinuxPerf" begin

Expand All @@ -21,7 +21,29 @@ using LinuxPerf: make_bench, enable!, disable!, reset!, reasonable_defaults, cou
end
g(zeros(10000))

counters(bench)
results = counters(bench)
close(bench)

true # Succeeded without any exceptions...
end

@test begin
bench = make_bench(reasonable_defaults);
@noinline function g(a)
enable_all!()
c = 0
for x in a
if x > 0
c += 1
end
end
disable_all!()
c
end
g(zeros(10000))

results = counters(bench)
close(bench)

true # Succeeded without any exceptions...
end
Expand Down