blob: b8baf16fd2dc9747e105104d873fd3775d20bfba [file] [log] [blame]
Nan Zhang17f27672018-12-12 16:01:49 -08001// Copyright 2018 Google Inc. All Rights Reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package metrics
16
17import (
18 "time"
19
20 "android/soong/ui/metrics/metrics_proto"
21 "android/soong/ui/tracer"
22)
23
24type timeEvent struct {
25 desc string
26 name string
27
28 atNanos uint64 // timestamp measured in nanoseconds since the reference date
29}
30
31type TimeTracer interface {
32 Begin(name, desc string, thread tracer.Thread)
Patrice Arruda0cc5b212019-06-14 15:27:46 -070033 End(thread tracer.Thread) soong_metrics_proto.PerfInfo
Nan Zhang17f27672018-12-12 16:01:49 -080034}
35
36type timeTracerImpl struct {
37 activeEvents []timeEvent
38}
39
40var _ TimeTracer = &timeTracerImpl{}
41
42func (t *timeTracerImpl) now() uint64 {
43 return uint64(time.Now().UnixNano())
44}
45
46func (t *timeTracerImpl) Begin(name, desc string, thread tracer.Thread) {
47 t.beginAt(name, desc, t.now())
48}
49
50func (t *timeTracerImpl) beginAt(name, desc string, atNanos uint64) {
51 t.activeEvents = append(t.activeEvents, timeEvent{name: name, desc: desc, atNanos: atNanos})
52}
53
Patrice Arruda0cc5b212019-06-14 15:27:46 -070054func (t *timeTracerImpl) End(thread tracer.Thread) soong_metrics_proto.PerfInfo {
Nan Zhang17f27672018-12-12 16:01:49 -080055 return t.endAt(t.now())
56}
57
Patrice Arruda0cc5b212019-06-14 15:27:46 -070058func (t *timeTracerImpl) endAt(atNanos uint64) soong_metrics_proto.PerfInfo {
Nan Zhang17f27672018-12-12 16:01:49 -080059 if len(t.activeEvents) < 1 {
60 panic("Internal error: No pending events for endAt to end!")
61 }
62 lastEvent := t.activeEvents[len(t.activeEvents)-1]
63 t.activeEvents = t.activeEvents[:len(t.activeEvents)-1]
64 realTime := atNanos - lastEvent.atNanos
65
Patrice Arruda0cc5b212019-06-14 15:27:46 -070066 return soong_metrics_proto.PerfInfo{
Nan Zhang17f27672018-12-12 16:01:49 -080067 Desc: &lastEvent.desc,
68 Name: &lastEvent.name,
69 StartTime: &lastEvent.atNanos,
70 RealTime: &realTime}
71}