Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:44:34

0001 //===-- llvm/Support/Timer.h - Interval Timing Support ----------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 
0009 #ifndef LLVM_SUPPORT_TIMER_H
0010 #define LLVM_SUPPORT_TIMER_H
0011 
0012 #include "llvm/ADT/StringMap.h"
0013 #include "llvm/ADT/StringRef.h"
0014 #include "llvm/Support/DataTypes.h"
0015 #include "llvm/Support/Mutex.h"
0016 #include <cassert>
0017 #include <memory>
0018 #include <string>
0019 #include <vector>
0020 
0021 namespace llvm {
0022 
0023 class TimerGlobals;
0024 class TimerGroup;
0025 class raw_ostream;
0026 
0027 class TimeRecord {
0028   double WallTime = 0.0;             ///< Wall clock time elapsed in seconds.
0029   double UserTime = 0.0;             ///< User time elapsed.
0030   double SystemTime = 0.0;           ///< System time elapsed.
0031   ssize_t MemUsed = 0;               ///< Memory allocated (in bytes).
0032   uint64_t InstructionsExecuted = 0; ///< Number of instructions executed
0033 public:
0034   TimeRecord() = default;
0035 
0036   /// Get the current time and memory usage.  If Start is true we get the memory
0037   /// usage before the time, otherwise we get time before memory usage.  This
0038   /// matters if the time to get the memory usage is significant and shouldn't
0039   /// be counted as part of a duration.
0040   static TimeRecord getCurrentTime(bool Start = true);
0041 
0042   double getProcessTime() const { return UserTime + SystemTime; }
0043   double getUserTime() const { return UserTime; }
0044   double getSystemTime() const { return SystemTime; }
0045   double getWallTime() const { return WallTime; }
0046   ssize_t getMemUsed() const { return MemUsed; }
0047   uint64_t getInstructionsExecuted() const { return InstructionsExecuted; }
0048 
0049   bool operator<(const TimeRecord &T) const {
0050     // Sort by Wall Time elapsed, as it is the only thing really accurate
0051     return WallTime < T.WallTime;
0052   }
0053 
0054   void operator+=(const TimeRecord &RHS) {
0055     WallTime += RHS.WallTime;
0056     UserTime += RHS.UserTime;
0057     SystemTime += RHS.SystemTime;
0058     MemUsed += RHS.MemUsed;
0059     InstructionsExecuted += RHS.InstructionsExecuted;
0060   }
0061   void operator-=(const TimeRecord &RHS) {
0062     WallTime -= RHS.WallTime;
0063     UserTime -= RHS.UserTime;
0064     SystemTime -= RHS.SystemTime;
0065     MemUsed -= RHS.MemUsed;
0066     InstructionsExecuted -= RHS.InstructionsExecuted;
0067   }
0068 
0069   /// Print the current time record to \p OS, with a breakdown showing
0070   /// contributions to the \p Total time record.
0071   void print(const TimeRecord &Total, raw_ostream &OS) const;
0072 };
0073 
0074 /// This class is used to track the amount of time spent between invocations of
0075 /// its startTimer()/stopTimer() methods.  Given appropriate OS support it can
0076 /// also keep track of the RSS of the program at various points.  By default,
0077 /// the Timer will print the amount of time it has captured to standard error
0078 /// when the last timer is destroyed, otherwise it is printed when its
0079 /// TimerGroup is destroyed.  Timers do not print their information if they are
0080 /// never started.
0081 class Timer {
0082   TimeRecord Time;          ///< The total time captured.
0083   TimeRecord StartTime;     ///< The time startTimer() was last called.
0084   std::string Name;         ///< The name of this time variable.
0085   std::string Description;  ///< Description of this time variable.
0086   bool Running = false;     ///< Is the timer currently running?
0087   bool Triggered = false;   ///< Has the timer ever been triggered?
0088   TimerGroup *TG = nullptr; ///< The TimerGroup this Timer is in.
0089 
0090   Timer **Prev = nullptr;   ///< Pointer to \p Next of previous timer in group.
0091   Timer *Next = nullptr;    ///< Next timer in the group.
0092 public:
0093   explicit Timer(StringRef TimerName, StringRef TimerDescription) {
0094     init(TimerName, TimerDescription);
0095   }
0096   Timer(StringRef TimerName, StringRef TimerDescription, TimerGroup &tg) {
0097     init(TimerName, TimerDescription, tg);
0098   }
0099   Timer(const Timer &RHS) {
0100     assert(!RHS.TG && "Can only copy uninitialized timers");
0101   }
0102   const Timer &operator=(const Timer &T) {
0103     assert(!TG && !T.TG && "Can only assign uninit timers");
0104     return *this;
0105   }
0106   ~Timer();
0107 
0108   /// Create an uninitialized timer, client must use 'init'.
0109   explicit Timer() = default;
0110   void init(StringRef TimerName, StringRef TimerDescription);
0111   void init(StringRef TimerName, StringRef TimerDescription, TimerGroup &tg);
0112 
0113   const std::string &getName() const { return Name; }
0114   const std::string &getDescription() const { return Description; }
0115   bool isInitialized() const { return TG != nullptr; }
0116 
0117   /// Check if the timer is currently running.
0118   bool isRunning() const { return Running; }
0119 
0120   /// Check if startTimer() has ever been called on this timer.
0121   bool hasTriggered() const { return Triggered; }
0122 
0123   /// Start the timer running.  Time between calls to startTimer/stopTimer is
0124   /// counted by the Timer class.  Note that these calls must be correctly
0125   /// paired.
0126   void startTimer();
0127 
0128   /// Stop the timer.
0129   void stopTimer();
0130 
0131   /// Clear the timer state.
0132   void clear();
0133 
0134   /// Stop the timer and start another timer.
0135   void yieldTo(Timer &);
0136 
0137   /// Return the duration for which this timer has been running.
0138   TimeRecord getTotalTime() const { return Time; }
0139 
0140 private:
0141   friend class TimerGroup;
0142 };
0143 
0144 /// The TimeRegion class is used as a helper class to call the startTimer() and
0145 /// stopTimer() methods of the Timer class.  When the object is constructed, it
0146 /// starts the timer specified as its argument.  When it is destroyed, it stops
0147 /// the relevant timer.  This makes it easy to time a region of code.
0148 class TimeRegion {
0149   Timer *T;
0150   TimeRegion(const TimeRegion &) = delete;
0151 
0152 public:
0153   explicit TimeRegion(Timer &t) : T(&t) {
0154     T->startTimer();
0155   }
0156   explicit TimeRegion(Timer *t) : T(t) {
0157     if (T) T->startTimer();
0158   }
0159   ~TimeRegion() {
0160     if (T) T->stopTimer();
0161   }
0162 };
0163 
0164 /// This class is basically a combination of TimeRegion and Timer.  It allows
0165 /// you to declare a new timer, AND specify the region to time, all in one
0166 /// statement.  All timers with the same name are merged.  This is primarily
0167 /// used for debugging and for hunting performance problems.
0168 struct NamedRegionTimer : public TimeRegion {
0169   explicit NamedRegionTimer(StringRef Name, StringRef Description,
0170                             StringRef GroupName,
0171                             StringRef GroupDescription, bool Enabled = true);
0172 };
0173 
0174 /// The TimerGroup class is used to group together related timers into a single
0175 /// report that is printed when the TimerGroup is destroyed.  It is illegal to
0176 /// destroy a TimerGroup object before all of the Timers in it are gone.  A
0177 /// TimerGroup can be specified for a newly created timer in its constructor.
0178 class TimerGroup {
0179   struct PrintRecord {
0180     TimeRecord Time;
0181     std::string Name;
0182     std::string Description;
0183 
0184     PrintRecord(const PrintRecord &Other) = default;
0185     PrintRecord &operator=(const PrintRecord &Other) = default;
0186     PrintRecord(const TimeRecord &Time, const std::string &Name,
0187                 const std::string &Description)
0188       : Time(Time), Name(Name), Description(Description) {}
0189 
0190     bool operator <(const PrintRecord &Other) const {
0191       return Time < Other.Time;
0192     }
0193   };
0194   std::string Name;
0195   std::string Description;
0196   Timer *FirstTimer = nullptr; ///< First timer in the group.
0197   std::vector<PrintRecord> TimersToPrint;
0198 
0199   TimerGroup **Prev; ///< Pointer to Next field of previous timergroup in list.
0200   TimerGroup *Next;  ///< Pointer to next timergroup in list.
0201   TimerGroup(const TimerGroup &TG) = delete;
0202   void operator=(const TimerGroup &TG) = delete;
0203 
0204   friend class TimerGlobals;
0205   explicit TimerGroup(StringRef Name, StringRef Description,
0206                       sys::SmartMutex<true> &lock);
0207 
0208 public:
0209   explicit TimerGroup(StringRef Name, StringRef Description);
0210 
0211   explicit TimerGroup(StringRef Name, StringRef Description,
0212                       const StringMap<TimeRecord> &Records);
0213 
0214   ~TimerGroup();
0215 
0216   void setName(StringRef NewName, StringRef NewDescription) {
0217     Name.assign(NewName.begin(), NewName.end());
0218     Description.assign(NewDescription.begin(), NewDescription.end());
0219   }
0220 
0221   /// Print any started timers in this group, optionally resetting timers after
0222   /// printing them.
0223   void print(raw_ostream &OS, bool ResetAfterPrint = false);
0224 
0225   /// Clear all timers in this group.
0226   void clear();
0227 
0228   /// This static method prints all timers.
0229   static void printAll(raw_ostream &OS);
0230 
0231   /// Clear out all timers. This is mostly used to disable automatic
0232   /// printing on shutdown, when timers have already been printed explicitly
0233   /// using \c printAll or \c printJSONValues.
0234   static void clearAll();
0235 
0236   const char *printJSONValues(raw_ostream &OS, const char *delim);
0237 
0238   /// Prints all timers as JSON key/value pairs.
0239   static const char *printAllJSONValues(raw_ostream &OS, const char *delim);
0240 
0241   /// Ensure global objects required for statistics printing are initialized.
0242   /// This function is used by the Statistic code to ensure correct order of
0243   /// global constructors and destructors.
0244   static void constructForStatistics();
0245 
0246   /// This makes the timer globals unmanaged, and lets the user manage the
0247   /// lifetime.
0248   static void *acquireTimerGlobals();
0249 
0250 private:
0251   friend class Timer;
0252   friend void PrintStatisticsJSON(raw_ostream &OS);
0253   void addTimer(Timer &T);
0254   void removeTimer(Timer &T);
0255   void prepareToPrintList(bool reset_time = false);
0256   void PrintQueuedTimers(raw_ostream &OS);
0257   void printJSONValue(raw_ostream &OS, const PrintRecord &R,
0258                       const char *suffix, double Value);
0259 };
0260 
0261 } // end namespace llvm
0262 
0263 #endif