blob: cca5632b0292fdc41a35048153d58b7bcb22c3e1 [file] [log] [blame]
Eanna O Cathain2f0ddb62022-03-03 15:58:10 +00001//
2// Copyright © 2022 Arm Ltd and Contributors. All rights reserved.
3// SPDX-License-Identifier: MIT
4//
5
6#pragma once
7#include <chrono>
8#include <iostream>
9#include <string>
10
11using namespace std::chrono;
12
13namespace common
14{
15/**
16* @brief Used for meausuring performance of specific actions in the code.
17 * Profiling should be enabled with a parameter passed to the constructor and
18 * it's disabled by default.
19 * In order to measure timing, wrap the desired code section with
20 * ProfilingStart() and ProfilingStopAndPrintUs(title)
21*/
22class Profiling {
23private:
24
25 struct group_thousands : std::numpunct<char>
26 {
27 std::string do_grouping() const override { return "\3"; }
28 };
29
30 bool mProfilingEnabled{};
31 steady_clock::time_point mStart{};
32 steady_clock::time_point mStop{};
33public:
34 Profiling() : mProfilingEnabled(false) {};
35
36 /**
37 * @brief Initializes the profiling object.
38 *
39 * * @param[in] isEnabled - Enables the profiling computation and prints.
40 */
41 explicit Profiling(bool isEnabled) : mProfilingEnabled(isEnabled) {};
42
43/**
44* @brief Starts the profiling measurement.
45*
46*/
47
48 void ProfilingStart()
49 {
50 if (mProfilingEnabled)
51 {
52 mStart = steady_clock::now();
53 }
54 }
55
56/**
57* @brief Stops the profiling measurement, without printing the results.
58*
59*/
60 auto ProfilingStop()
61 {
62 if (mProfilingEnabled)
63 {
64 mStop = steady_clock::now();
65 }
66 }
67
68/**
69* @brief Get the measurement result in micro-seconds.
70*
71*/
72 auto ProfilingGetUs()
73 {
74 return mProfilingEnabled ? duration_cast<microseconds>(mStop - mStart).count() : 0;
75 }
76
77/**
78* @brief Stop the profiling measurement and print the result in micro-seconds.
79*
80*/
81 void ProfilingStopAndPrintUs(const std::string &title)
82 {
83 ProfilingStop();
84 if (mProfilingEnabled) {
85 std::cout.imbue(std::locale(std::cout.getloc(), new group_thousands));
86 std::cout << "Profiling: " << title << ": " << ProfilingGetUs() << " uSeconds" << std::endl;
87 }
88 }
89};
90}// namespace common