62 lines · cpp
1//===- ActionProfiler.cpp - Profiling Actions *- C++ -*-=====================//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8 9#include "mlir/Debug/Observers/ActionProfiler.h"10#include "mlir/Debug/BreakpointManager.h"11#include "mlir/IR/Action.h"12#include "llvm/Support/Threading.h"13#include "llvm/Support/raw_ostream.h"14#include <chrono>15 16using namespace mlir;17using namespace mlir::tracing;18 19//===----------------------------------------------------------------------===//20// ActionProfiler21//===----------------------------------------------------------------------===//22void ActionProfiler::beforeExecute(const ActionActiveStack *action,23 Breakpoint *breakpoint, bool willExecute) {24 print(action, "B"); // begin event.25}26 27void ActionProfiler::afterExecute(const ActionActiveStack *action) {28 print(action, "E"); // end event.29}30 31// Print an event in JSON format.32void ActionProfiler::print(const ActionActiveStack *action,33 llvm::StringRef phase) {34 // Create the event.35 std::string str;36 llvm::raw_string_ostream event(str);37 event << "{";38 event << R"("name": ")" << action->getAction().getTag() << "\", ";39 event << R"("cat": "PERF", )";40 event << R"("ph": ")" << phase << "\", ";41 event << R"("pid": 0, )";42 event << R"("tid": )" << llvm::get_threadid() << ", ";43 auto ts = std::chrono::steady_clock::now() - startTime;44 event << R"("ts": )"45 << std::chrono::duration_cast<std::chrono::microseconds>(ts).count();46 if (phase == "B") {47 event << R"(, "args": {)";48 event << R"("desc": ")";49 action->getAction().print(event);50 event << "\"}";51 }52 event << "}";53 54 // Print the event.55 std::lock_guard<std::mutex> guard(mutex);56 if (printComma)57 os << ",\n";58 printComma = true;59 os << str;60 os.flush();61}62