TimeRecord.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. //
  2. // Created by zx on 22-11-3.
  3. //
  4. #include "TimeRecord.h"
  5. #include <iostream>
  6. std::map<std::string, TimeRecord::Record> TimeRecord::records_=std::map<std::string, TimeRecord::Record>();
  7. void TimeRecord::PrintAll()
  8. {
  9. std::cout <<">> ===== Printing run time ====="<<std::endl;
  10. for (const auto& r : records_) {
  11. std::cout<< "> [ " << r.first << " ] average time usage: "
  12. << std::accumulate(r.second.time_usage_in_ms_.begin(), r.second.time_usage_in_ms_.end(), 0.0) /
  13. double(r.second.time_usage_in_ms_.size())
  14. << " ms , called times: " << r.second.time_usage_in_ms_.size()<<std::endl;
  15. }
  16. std::cout << ">>> ===== Printing run time end ====="<<std::endl;
  17. }
  18. void TimeRecord::DumpIntoFile(const std::string& file_name)
  19. {
  20. std::ofstream ofs(file_name, std::ios::out);
  21. if (!ofs.is_open()) {
  22. std::cout << "Failed to open file: " << file_name<<std::endl;
  23. return;
  24. } else {
  25. std::cout << "Dump Time Records into file: " << file_name<<std::endl;
  26. }
  27. size_t max_length = 0;
  28. for (const auto& iter : records_) {
  29. ofs << iter.first << ", ";
  30. if (iter.second.time_usage_in_ms_.size() > max_length) {
  31. max_length = iter.second.time_usage_in_ms_.size();
  32. }
  33. }
  34. ofs << std::endl;
  35. for (size_t i = 0; i < max_length; ++i) {
  36. for (const auto& iter : records_) {
  37. if (i < iter.second.time_usage_in_ms_.size()) {
  38. ofs << iter.second.time_usage_in_ms_[i] << ",";
  39. } else {
  40. ofs << ",";
  41. }
  42. }
  43. ofs << std::endl;
  44. }
  45. ofs.close();
  46. }
  47. double TimeRecord::GetMeanTime(const std::string& func_name)
  48. {
  49. if (records_.find(func_name) == records_.end()) {
  50. return 0.0;
  51. }
  52. auto r = records_[func_name];
  53. return std::accumulate(r.time_usage_in_ms_.begin(), r.time_usage_in_ms_.end(), 0.0) /
  54. double(r.time_usage_in_ms_.size());
  55. }