timings.h 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #ifndef CARBON_TOOLCHAIN_BASE_TIMINGS_H_
  5. #define CARBON_TOOLCHAIN_BASE_TIMINGS_H_
  6. #include <chrono>
  7. #include "llvm/ADT/SmallVector.h"
  8. #include "llvm/ADT/StringRef.h"
  9. #include "toolchain/base/yaml.h"
  10. namespace Carbon {
  11. // Helps track timings for a compile.
  12. class Timings {
  13. public:
  14. // Records a timing for a scope, if the timings object is present.
  15. class ScopedTiming {
  16. public:
  17. // The `timings` may be null, in which case the `ScopedTiming` is a no-op.
  18. explicit ScopedTiming(Timings* timings, llvm::StringRef label)
  19. : timings_(timings),
  20. label_(label),
  21. start_(timings ? std::chrono::steady_clock::now()
  22. : std::chrono::steady_clock::time_point::min()) {}
  23. ~ScopedTiming() {
  24. if (timings_) {
  25. timings_->Add(label_, std::chrono::steady_clock::now() - start_);
  26. }
  27. }
  28. private:
  29. Timings* timings_;
  30. llvm::StringRef label_;
  31. std::chrono::steady_clock::time_point start_;
  32. };
  33. // Adds tracking for nanoseconds, paired with the given label.
  34. auto Add(llvm::StringRef label, std::chrono::nanoseconds nanoseconds)
  35. -> void {
  36. timings_.push_back(
  37. {.label = std::string(label), .nanoseconds = nanoseconds});
  38. }
  39. auto OutputYaml(llvm::StringRef filename) const -> Yaml::OutputMapping {
  40. // Explicitly copy the filename.
  41. return Yaml::OutputMapping([&, filename](Yaml::OutputMapping::Map map) {
  42. map.Add("filename", filename);
  43. map.Add("nanoseconds",
  44. Yaml::OutputMapping([&](Yaml::OutputMapping::Map label_map) {
  45. std::chrono::nanoseconds total_nanoseconds(0);
  46. for (const auto& entry : timings_) {
  47. total_nanoseconds += entry.nanoseconds;
  48. label_map.Add(entry.label, static_cast<int64_t>(
  49. entry.nanoseconds.count()));
  50. }
  51. label_map.Add("Total",
  52. static_cast<int64_t>(total_nanoseconds.count()));
  53. }));
  54. });
  55. }
  56. private:
  57. // Timing for a specific label.
  58. struct Entry {
  59. std::string label;
  60. std::chrono::nanoseconds nanoseconds;
  61. };
  62. // The accumulated data on timings.
  63. llvm::SmallVector<Entry> timings_;
  64. };
  65. } // namespace Carbon
  66. #endif // CARBON_TOOLCHAIN_BASE_TIMINGS_H_