Skip to content

Commit 7b16bcd

Browse files
authored
Support RAII for C++ and ctx manager for Python (#66)
1 parent db8fe9e commit 7b16bcd

4 files changed

Lines changed: 38 additions & 9 deletions

File tree

lib/include/rtm/probe.h

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,23 @@
1212

1313
namespace rtm
1414
{
15+
class Probe;
16+
17+
class ProbeGuard
18+
{
19+
public:
20+
ProbeGuard(Probe& probe);
21+
~ProbeGuard();
22+
23+
ProbeGuard(ProbeGuard const&) = delete;
24+
ProbeGuard(ProbeGuard&&) = delete;
25+
ProbeGuard& operator=(ProbeGuard const&) = delete;
26+
ProbeGuard& operator=(ProbeGuard&&) = delete;
27+
28+
private:
29+
Probe* probe_;
30+
};
31+
1532
class Probe
1633
{
1734
public:

lib/py_bindings/src/lib_py.cc

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,9 @@ namespace rtm
8989
.def("set_threshold", [](Probe& self, uint64_t threshold_ns)
9090
{
9191
self.set_threshold(nanoseconds{threshold_ns});
92-
}, "threshold_ns"_a);
92+
}, "threshold_ns"_a)
93+
.def("__enter__", [](Probe& self) -> Probe& { self.log(); return self; })
94+
.def("__exit__", [](Probe& self, nb::handle, nb::handle, nb::handle) { self.log(); });
9395

9496
nb::bind_vector<std::vector<float>>(m, "FVector");
9597
nb::bind_vector<std::vector<nanoseconds>>(m, "nsVector");

lib/src/probe.cc

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,17 @@
88

99
namespace rtm
1010
{
11+
ProbeGuard::ProbeGuard(Probe& probe)
12+
: probe_(&probe)
13+
{
14+
probe_->log();
15+
}
16+
17+
ProbeGuard::~ProbeGuard()
18+
{
19+
probe_->log();
20+
}
21+
1122
Probe::Probe()
1223
{
1324
samples_.reserve(MAX_SAMPLES);

py_bindings/examples/probe.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,16 +19,15 @@
1919
TARGET = 0.001 # 1 ms
2020

2121
for i in range(400000):
22-
p.log_start()
23-
start = time.perf_counter()
22+
with p:
23+
start = time.perf_counter()
2424

25-
# ---- dummy computation ----
26-
x = i * i
25+
# ---- dummy computation ----
26+
x = i * i
2727

28-
# ---- adjust to hit 1 ms ----
29-
elapsed = time.perf_counter() - start
30-
remaining = TARGET - elapsed
31-
p.log_end()
28+
# ---- adjust to hit 1 ms ----
29+
elapsed = time.perf_counter() - start
30+
remaining = TARGET - elapsed
3231

3332
if remaining > 0:
3433
time.sleep(remaining)

0 commit comments

Comments
 (0)