timer.cc 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include <cstdlib>
  2. #include <cstring>
  3. #include <fstream>
  4. #include <iomanip>
  5. #include "timer.h"
  6. using namespace std;
  7. double timer::CPU_speed_in_MHz = timer::get_CPU_speed_in_MHz();
  8. double timer::get_CPU_speed_in_MHz()
  9. {
  10. #if defined __linux__
  11. ifstream infile("/proc/cpuinfo");
  12. char buffer[256], *colon;
  13. while (infile.good()) {
  14. infile.getline(buffer, 256);
  15. if (strncmp("cpu MHz", buffer, 7) == 0 && (colon = strchr(buffer, ':')) != 0)
  16. return atof(colon + 2);
  17. }
  18. #endif
  19. return 0.0;
  20. }
  21. void timer::print_time(ostream &str, const char *which, double time) const
  22. {
  23. static const char *units[] = { " ns", " us", " ms", " s", " ks", 0 };
  24. const char **unit = units;
  25. time = 1000.0 * time / CPU_speed_in_MHz;
  26. while (time >= 999.5 && unit[1] != 0) {
  27. time /= 1000.0;
  28. ++ unit;
  29. }
  30. str << which << " = " << setprecision(3) << setw(4) << time << *unit;
  31. }
  32. ostream &timer::print(ostream &str)
  33. {
  34. str << left << setw(25) << (name != 0 ? name : "timer") << ": " << right;
  35. if (CPU_speed_in_MHz == 0)
  36. str << "could not determine CPU speed\n";
  37. else if (count > 0) {
  38. double total = static_cast<double>(total_time);
  39. print_time(str, "avg", total / static_cast<double>(count));
  40. print_time(str, ", total", total);
  41. str << ", count = " << setw(9) << count << '\n';
  42. }
  43. else
  44. str << "not used\n";
  45. return str;
  46. }
  47. ostream &operator << (ostream &str, class timer &timer)
  48. {
  49. return timer.print(str);
  50. }
  51. double timer::getTimeInSeconds()
  52. {
  53. double total = static_cast<double>(total_time);
  54. double res = (total / 1000000.0) / CPU_speed_in_MHz;
  55. return res;
  56. }