1 // Copyright 2011 Google Inc. All Rights Reserved.
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
7 // http://www.apache.org/licenses/LICENSE-2.0
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.
29 Metrics* g_metrics = NULL;
34 /// Compute a platform-specific high-res timer value that fits into an int64.
35 int64_t HighResTimer() {
37 if (gettimeofday(&tv, NULL) < 0)
38 Fatal("gettimeofday: %s", strerror(errno));
39 return (int64_t)tv.tv_sec * 1000*1000 + tv.tv_usec;
42 /// Convert a delta of HighResTimer() values to microseconds.
43 int64_t TimerToMicros(int64_t dt) {
44 // No conversion necessary.
48 int64_t LargeIntegerToInt64(const LARGE_INTEGER& i) {
49 return ((int64_t)i.HighPart) << 32 | i.LowPart;
52 int64_t HighResTimer() {
53 LARGE_INTEGER counter;
54 if (!QueryPerformanceCounter(&counter))
55 Fatal("QueryPerformanceCounter: %s", GetLastErrorString().c_str());
56 return LargeIntegerToInt64(counter);
59 int64_t TimerToMicros(int64_t dt) {
60 static int64_t ticks_per_sec = 0;
63 if (!QueryPerformanceFrequency(&freq))
64 Fatal("QueryPerformanceFrequency: %s", GetLastErrorString().c_str());
65 ticks_per_sec = LargeIntegerToInt64(freq);
68 // dt is in ticks. We want microseconds.
69 return (dt * 1000000) / ticks_per_sec;
73 } // anonymous namespace
75 ScopedMetric::ScopedMetric(Metric* metric) {
79 start_ = HighResTimer();
81 ScopedMetric::~ScopedMetric() {
85 int64_t dt = TimerToMicros(HighResTimer() - start_);
89 Metric* Metrics::NewMetric(const string& name) {
90 Metric* metric = new Metric;
94 metrics_.push_back(metric);
98 void Metrics::Report() {
100 for (vector<Metric*>::iterator i = metrics_.begin();
101 i != metrics_.end(); ++i) {
102 width = max((int)(*i)->name.size(), width);
105 printf("%-*s\t%-6s\t%9s\t%s\n", width,
106 "metric", "count", "total (ms)" , "avg (us)");
107 for (vector<Metric*>::iterator i = metrics_.begin();
108 i != metrics_.end(); ++i) {
110 double total = metric->sum / (double)1000;
111 double avg = metric->sum / (double)metric->count;
112 printf("%-*s\t%-6d\t%-8.1f\t%.1f\n", width, metric->name.c_str(),
113 metric->count, total, avg);