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.
31 Metrics* g_metrics = NULL;
36 /// Compute a platform-specific high-res timer value that fits into an int64.
37 int64_t HighResTimer() {
39 if (gettimeofday(&tv, NULL) < 0)
40 Fatal("gettimeofday: %s", strerror(errno));
41 return (int64_t)tv.tv_sec * 1000*1000 + tv.tv_usec;
44 /// Convert a delta of HighResTimer() values to microseconds.
45 int64_t TimerToMicros(int64_t dt) {
46 // No conversion necessary.
50 int64_t LargeIntegerToInt64(const LARGE_INTEGER& i) {
51 return ((int64_t)i.HighPart) << 32 | i.LowPart;
54 int64_t HighResTimer() {
55 LARGE_INTEGER counter;
56 if (!QueryPerformanceCounter(&counter))
57 Fatal("QueryPerformanceCounter: %s", GetLastErrorString().c_str());
58 return LargeIntegerToInt64(counter);
61 int64_t TimerToMicros(int64_t dt) {
62 static int64_t ticks_per_sec = 0;
65 if (!QueryPerformanceFrequency(&freq))
66 Fatal("QueryPerformanceFrequency: %s", GetLastErrorString().c_str());
67 ticks_per_sec = LargeIntegerToInt64(freq);
70 // dt is in ticks. We want microseconds.
71 return (dt * 1000000) / ticks_per_sec;
75 } // anonymous namespace
78 ScopedMetric::ScopedMetric(Metric* metric) {
82 start_ = HighResTimer();
84 ScopedMetric::~ScopedMetric() {
88 int64_t dt = TimerToMicros(HighResTimer() - start_);
92 Metric* Metrics::NewMetric(const string& name) {
93 Metric* metric = new Metric;
97 metrics_.push_back(metric);
101 void Metrics::Report() {
103 for (vector<Metric*>::iterator i = metrics_.begin();
104 i != metrics_.end(); ++i) {
105 width = max((int)(*i)->name.size(), width);
108 printf("%-*s\t%-6s\t%-9s\t%s\n", width,
109 "metric", "count", "avg (us)", "total (ms)");
110 for (vector<Metric*>::iterator i = metrics_.begin();
111 i != metrics_.end(); ++i) {
113 double total = metric->sum / (double)1000;
114 double avg = metric->sum / (double)metric->count;
115 printf("%-*s\t%-6d\t%-8.1f\t%.1f\n", width, metric->name.c_str(),
116 metric->count, avg, total);
120 uint64_t Stopwatch::Now() const {
121 return TimerToMicros(HighResTimer());
124 int64_t GetTimeMillis() {
125 return TimerToMicros(HighResTimer()) / 1000;