xref: /aosp_15_r20/external/stg/runtime.cc (revision 9e3b08ae94a55201065475453d799e8b1378bea6)
1 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
2 // -*- mode: C++ -*-
3 //
4 // Copyright 2021-2023 Google LLC
5 //
6 // Licensed under the Apache License v2.0 with LLVM Exceptions (the
7 // "License"); you may not use this file except in compliance with the
8 // License.  You may obtain a copy of the License at
9 //
10 //     https://llvm.org/LICENSE.txt
11 //
12 // Unless required by applicable law or agreed to in writing, software
13 // distributed under the License is distributed on an "AS IS" BASIS,
14 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 // See the License for the specific language governing permissions and
16 // limitations under the License.
17 //
18 // Author: Giuliano Procida
19 
20 #include "runtime.h"
21 
22 #include <time.h>
23 
24 #include <iomanip>
25 #include <ostream>
26 
27 namespace stg {
28 
operator <<(std::ostream & os,const Frequencies & frequencies)29 std::ostream& operator<<(std::ostream& os, const Frequencies& frequencies) {
30   bool separate = false;
31   for (const auto& [item, frequency] : frequencies.counts) {
32     if (separate) {
33       os << ' ';
34     } else {
35       separate = true;
36     }
37     os << '[' << item << "]=" << frequency;
38   }
39   return os;
40 }
41 
operator <<(std::ostream & os,const Nanoseconds & value)42 std::ostream& operator<<(std::ostream& os, const Nanoseconds& value) {
43   const auto millis = value.ns / 1'000'000;
44   const auto nanos = value.ns % 1'000'000;
45   // fill needs to be reset; width is reset automatically
46   return os << millis << '.' << std::setfill('0') << std::setw(6) << nanos
47             << std::setfill(' ') << " ms";
48 }
49 
Time(Runtime & runtime,const char * name)50 Time::Time(Runtime& runtime, const char* name)
51     : runtime_(runtime), name_(name) {
52   clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start_);
53 }
54 
~Time()55 Time::~Time() {
56   struct timespec finish;
57   clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &finish);
58   const auto seconds = finish.tv_sec - start_.tv_sec;
59   const auto nanos = finish.tv_nsec - start_.tv_nsec;
60   const Nanoseconds value(seconds * 1'000'000'000 + nanos);
61   runtime_.PrintMetric(name_, value);
62 }
63 
Counter(Runtime & runtime,const char * name)64 Counter::Counter(Runtime& runtime, const char* name)
65     : runtime_(runtime), name_(name), value_(0) {
66 }
67 
~Counter()68 Counter::~Counter() {
69   runtime_.PrintMetric(name_, value_);
70 }
71 
Histogram(Runtime & runtime,const char * name)72 Histogram::Histogram(Runtime& runtime, const char* name)
73     : runtime_(runtime), name_(name) {
74 }
75 
~Histogram()76 Histogram::~Histogram() {
77   runtime_.PrintMetric(name_, frequencies_);
78 }
79 
80 }  // namespace stg
81