• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// 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)
33	End(thread tracer.Thread) metrics_proto.PerfInfo
34}
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
54func (t *timeTracerImpl) End(thread tracer.Thread) metrics_proto.PerfInfo {
55	return t.endAt(t.now())
56}
57
58func (t *timeTracerImpl) endAt(atNanos uint64) metrics_proto.PerfInfo {
59	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
66	return metrics_proto.PerfInfo{
67		Desc:      &lastEvent.desc,
68		Name:      &lastEvent.name,
69		StartTime: &lastEvent.atNanos,
70		RealTime:  &realTime}
71}
72