Skip to content

Commit

Permalink
Move timer from testgen to lib folder.
Browse files Browse the repository at this point in the history
  • Loading branch information
fruffy committed Dec 16, 2022
1 parent b8e80bf commit 8d521bc
Show file tree
Hide file tree
Showing 7 changed files with 52 additions and 48 deletions.
1 change: 0 additions & 1 deletion backends/p4tools/common/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ set(
lib/model.cpp
lib/symbolic_env.cpp
lib/taint.cpp
lib/timer.cpp
lib/trace_events.cpp
lib/util.cpp
lib/zombie.cpp
Expand Down
10 changes: 5 additions & 5 deletions backends/p4tools/common/core/z3_solver.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@

#include "backends/p4tools/common/lib/formulae.h"
#include "backends/p4tools/common/lib/model.h"
#include "backends/p4tools/common/lib/timer.h"
#include "gsl/gsl-lite.hpp"
#include "ir/ir.h"
#include "ir/irutils.h"
Expand All @@ -25,6 +24,7 @@
#include "lib/exceptions.h"
#include "lib/indent.h"
#include "lib/log.h"
#include "lib/timer.h"

namespace P4Tools {

Expand Down Expand Up @@ -283,8 +283,8 @@ boost::optional<bool> Z3Solver::checkSat(const std::vector<const Constraint*>& a
}
Z3_LOG("checking satisfiability for %d assertions",
isIncremental ? z3solver.assertions().size() : z3Assertions.size());
ScopedTimer ctZ3("z3");
ScopedTimer ctCheckSat("checkSat");
Util::ScopedTimer ctZ3("z3");
Util::ScopedTimer ctCheckSat("checkSat");
z3::check_result result = isIncremental ? z3solver.check() : z3solver.check(z3Assertions);
switch (result) {
case z3::sat:
Expand Down Expand Up @@ -332,8 +332,8 @@ const Model* Z3Solver::getModel() const {
}
// Then, get the model and match each declaration in the model to its StateVariable.
try {
ScopedTimer ctZ3("z3");
ScopedTimer ctCheckSat("getModel");
Util::ScopedTimer ctZ3("z3");
Util::ScopedTimer ctCheckSat("getModel");
auto z3Model = z3solver.get_model();
Z3_LOG("z3 model:%s", toString(z3Model));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@
#include "backends/p4tools/common/core/solver.h"
#include "backends/p4tools/common/lib/formulae.h"
#include "backends/p4tools/common/lib/symbolic_env.h"
#include "backends/p4tools/common/lib/timer.h"
#include "backends/p4tools/common/lib/util.h"
#include "frontends/p4/optimizeExpressions.h"
#include "gsl/gsl-lite.hpp"
#include "ir/ir.h"
#include "ir/irutils.h"
#include "lib/error.h"
#include "lib/timer.h"
#include "midend/coverage.h"

#include "backends/p4tools/modules/testgen/core/program_info.h"
Expand Down Expand Up @@ -52,7 +52,7 @@ ExplorationStrategy::Branch::Branch(boost::optional<const Constraint*> c,
}

ExplorationStrategy::StepResult ExplorationStrategy::step(ExecutionState& state) {
ScopedTimer st("step");
Util::ScopedTimer st("step");
StepResult successors = evaluator.step(state);
// Assign branch ids to the branches. These integer branch ids are used by track-branches
// and selected (input) branches features.
Expand Down
9 changes: 5 additions & 4 deletions backends/p4tools/modules/testgen/lib/test_backend.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,14 @@
#include "backends/p4tools/common/lib/model.h"
#include "backends/p4tools/common/lib/symbolic_env.h"
#include "backends/p4tools/common/lib/taint.h"
#include "backends/p4tools/common/lib/timer.h"
#include "backends/p4tools/common/lib/trace_events.h"
#include "backends/p4tools/common/lib/util.h"
#include "frontends/p4/optimizeExpressions.h"
#include "ir/irutils.h"
#include "lib/error.h"
#include "lib/exceptions.h"
#include "lib/null.h"
#include "lib/timer.h"
#include "midend/coverage.h"

#include "backends/p4tools/modules/testgen/core/exploration_strategy/exploration_strategy.h"
Expand Down Expand Up @@ -158,8 +158,9 @@ bool TestBackEnd::run(const FinalState& state) {
P4::Coverage::logCoverage(allStatements, visitedStatements, executionState->getVisited());

// Output the test.
withTimer("backend",
[&] { testWriter->outputTest(testSpec, selectedBranches, testCount, coverage); });
Util::withTimer("backend", [&] {
testWriter->outputTest(testSpec, selectedBranches, testCount, coverage);
});

printTraces("============ End Test %1% ============\n", testCount);
testCount++;
Expand Down Expand Up @@ -267,7 +268,7 @@ bool TestBackEnd::printTestInfo(const ExecutionState* executionState, const Test

void TestBackEnd::printPerformanceReport() {
printFeature("performance", 4, "============ Timers ============");
for (const auto& c : getTimers()) {
for (const auto& c : Util::getTimers()) {
if (c.timerName.empty()) {
printFeature("performance", 4, "Total: %i ms", c.milliseconds);
} else {
Expand Down
2 changes: 2 additions & 0 deletions lib/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ set (LIBP4CTOOLKIT_SRCS
path.cpp
source_file.cpp
stringify.cpp
timer.cpp
)

set (LIBP4CTOOLKIT_HDRS
Expand Down Expand Up @@ -77,6 +78,7 @@ set (LIBP4CTOOLKIT_HDRS
stringify.h
stringref.h
symbitmatrix.h
timer.h
)

build_unified(LIBP4CTOOLKIT_SRCS ALL)
Expand Down
51 changes: 27 additions & 24 deletions backends/p4tools/common/lib/timer.cpp → lib/timer.cpp
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
#include "backends/p4tools/common/lib/timer.h"
#include "lib/timer.h"

#include <algorithm>
#include <chrono> // NOLINT linter forbids using chrono, but we don't have alternatives
#include <memory>
#include <unordered_map>
#include <utility>

namespace P4Tools {
namespace Util {

namespace {

Expand All @@ -19,10 +19,10 @@ using Clock = std::chrono::high_resolution_clock;
struct CounterEntry {
const char* name;
std::unordered_map<std::string, std::unique_ptr<CounterEntry>> counters;
Clock::duration duration;
Clock::duration duration{};

/// Lookup existing or create new child counter.
CounterEntry* open_subcounter(const char* name) {
CounterEntry* openSubcounter(const char* name) {
auto it = counters.find(name);
if (it == counters.end()) {
it = counters.emplace(name, new CounterEntry(name)).first;
Expand Down Expand Up @@ -50,52 +50,55 @@ struct RootCounter {
//
// however libgc cannot scan thread local data, which can lead to premature object
// garbage collection.
static RootCounter root;
root.counter.duration = Clock::now() - root.start;
return root;
static RootCounter ROOT;
ROOT.counter.duration = Clock::now() - ROOT.start;
return ROOT;
}

CounterEntry* getCurrent() const { return current; }

void setCurrent(CounterEntry* c) { current = c; }

private:
RootCounter() : counter("") {
current = &counter;
start = Clock::now();
}
RootCounter() : counter(""), current(&counter) { start = Clock::now(); }
};

} // namespace

#pragma GCC diagnostic push
#if !defined(__has_warning) || __has_warning("-Wsubobject-linkage")
#pragma GCC diagnostic ignored "-Wsubobject-linkage"
#endif
// RAII helper which manages lifetime of one timer invocation.
struct ScopedTimer::Ctx {
struct ScopedTimerCtx {
CounterEntry* parent = nullptr;
CounterEntry* self = nullptr;
Clock::time_point start_time;
Clock::time_point startTime;

explicit Ctx(const char* counter_name) {
start_time = Clock::now();
explicit ScopedTimerCtx(const char* timerName)
: parent(RootCounter::get().getCurrent()), self(parent->openSubcounter(timerName)) {
startTime = Clock::now();
// Push new active counter - the current active counter becomes the parent of this
// counter, and this counter becomes the current active counter.
parent = RootCounter::get().getCurrent();
self = parent->open_subcounter(counter_name);
RootCounter::get().setCurrent(self);
}
~Ctx() {
~ScopedTimerCtx() {
// Close the current timer invocation, measure time and add it to the counter.
auto duration = Clock::now() - start_time;
auto duration = Clock::now() - startTime;
self->add(duration);
// Restore previous counter as current.
RootCounter::get().setCurrent(parent);
}
};
#pragma GCC diagnostic pop


ScopedTimer::ScopedTimer(const char* name) : ctx(new ScopedTimerCtx(name)) {}

ScopedTimer::ScopedTimer(const char* name) : ctx(new ScopedTimer::Ctx(name)) {}
ScopedTimer::~ScopedTimer() = default;

void withTimer(const char* counter_name, std::function<void()> fn) {
ScopedTimer timer(counter_name);
void withTimer(const char* timerName, const std::function<void()>& fn) {
ScopedTimer timer(timerName);
fn();
}

Expand Down Expand Up @@ -127,9 +130,9 @@ static void formatCounters(std::vector<TimerEntry>& out, CounterEntry& current,

std::vector<TimerEntry> getTimers() {
std::vector<TimerEntry> ret;
std::string namePrefix = "";
std::string namePrefix;
formatCounters(ret, RootCounter::get().counter, namePrefix, 0);
return ret;
}

} // namespace P4Tools
} // namespace Util
23 changes: 11 additions & 12 deletions backends/p4tools/common/lib/timer.h → lib/timer.h
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
#ifndef BACKENDS_P4TOOLS_COMMON_LIB_TIMER_H_
#define BACKENDS_P4TOOLS_COMMON_LIB_TIMER_H_

#include <stddef.h>
#ifndef _LIB_TIMER_H_
#define _LIB_TIMER_H_

#include <cstddef>
#include <functional>
#include <memory>
#include <string>
#include <vector>

namespace P4Tools {
namespace Util {

/// Runs specified function and measures it's execution duration under specified timer name.
/// Timers can be nested. Measured durations are added under given timer name. In case of nested
Expand All @@ -23,7 +22,7 @@ namespace P4Tools {
/// });
///
/// uses two separate counters denoted as "A.C" and "B.C".
void withTimer(const char* timer_name, std::function<void()> fn);
void withTimer(const char* timerName, const std::function<void()>& fn);

struct TimerEntry {
/// Counter name. If a timer "Y" was invoked inside timer "X", its timer name is "X.Y".
Expand All @@ -37,6 +36,9 @@ struct TimerEntry {
/// Returns list of all timers for and their current values.
std::vector<TimerEntry> getTimers();

// Internal implementation.
struct ScopedTimerCtx;

/// Similar to withTimer function, measures execution time elapsed from instance creation to
/// destruction.
class ScopedTimer {
Expand All @@ -46,12 +48,9 @@ class ScopedTimer {
~ScopedTimer();

private:
// Internal implementation.
struct Ctx;

std::unique_ptr<Ctx> ctx;
std::unique_ptr<ScopedTimerCtx> ctx;
};

} // namespace P4Tools
} // namespace Util

#endif /* BACKENDS_P4TOOLS_COMMON_LIB_TIMER_H_ */
#endif /* _LIB_TIMER_H_ */

0 comments on commit 8d521bc

Please sign in to comment.