1 /* 2 * Copyright (C) 2014, The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #ifndef LATINIME_PROFILER_H 18 #define LATINIME_PROFILER_H 19 20 #ifdef FLAG_DO_PROFILE 21 22 #include "defines.h" 23 24 #include <ctime> 25 #include <unordered_map> 26 27 namespace latinime { 28 29 class Profiler final { 30 public: Profiler(const clockid_t clockId)31 Profiler(const clockid_t clockId) 32 : mClockId(clockId), mStartTime(getTimeInMicroSec()), mStartTimes(), mTimes(), 33 mCounters() {} 34 ~Profiler()35 ~Profiler() { 36 const float totalTime = 37 static_cast<float>(getTimeInMicroSec() - mStartTime) / 1000.f; 38 AKLOGI("Total time is %6.3f ms.", totalTime); 39 for (const auto &time : mTimes) { 40 AKLOGI("(%d): Used %4.2f%%, %8.4f ms. Called %d times.", time.first, 41 time.second / totalTime * 100.0f, time.second, mCounters[time.first]); 42 } 43 } 44 startTimer(const int id)45 void startTimer(const int id) { 46 mStartTimes[id] = getTimeInMicroSec(); 47 } 48 endTimer(const int id)49 void endTimer(const int id) { 50 mTimes[id] += static_cast<float>(getTimeInMicroSec() - mStartTimes[id]) / 1000.0f; 51 mCounters[id]++; 52 } 53 54 operator bool() const { return false; } 55 56 private: 57 DISALLOW_IMPLICIT_CONSTRUCTORS(Profiler); 58 59 const clockid_t mClockId; 60 int64_t mStartTime; 61 std::unordered_map<int, int64_t> mStartTimes; 62 std::unordered_map<int, float> mTimes; 63 std::unordered_map<int, int> mCounters; 64 getTimeInMicroSec()65 int64_t getTimeInMicroSec() { 66 timespec time; 67 clock_gettime(mClockId, &time); 68 return static_cast<int64_t>(time.tv_sec) * 1000000 69 + static_cast<int64_t>(time.tv_nsec) / 1000; 70 } 71 }; 72 } // namespace latinime 73 74 #define PROF_INIT Profiler __LATINIME__PROFILER__(CLOCK_THREAD_CPUTIME_ID) 75 #define PROF_TIMER_START(timer_id) __LATINIME__PROFILER__.startTimer(timer_id) 76 #define PROF_TIMER_END(timer_id) __LATINIME__PROFILER__.endTimer(timer_id) 77 78 #else // FLAG_DO_PROFILE 79 80 #define PROF_INIT 81 #define PROF_TIMER_START(timer_id) 82 #define PROF_TIMER_END(timer_id) 83 84 #endif // FLAG_DO_PROFILE 85 86 #endif /* LATINIME_PROFILER_H */ 87