File indexing completed on 2025-08-06 08:17:27
0001
0002
0003
0004
0005
0006
0007
0008
0009
0010
0011 #include "PHTimer.h"
0012
0013 #include <climits>
0014 #include <cmath>
0015 #include <cstddef>
0016 #include <fstream>
0017 #include <stdexcept>
0018
0019
0020
0021 PHTimer::Frequency PHTimer::_frequency = PHTimer::Frequency();
0022 const double PHTimer::_twopower32 = pow(2, 32);
0023
0024
0025 void PHTimer::Frequency::set_cpu_freq(const std::string& path)
0026 {
0027
0028 _frequency = 2e9;
0029
0030
0031 std::ifstream cpuProcFile(path);
0032 if (!cpuProcFile.is_open())
0033 {
0034 throw std::runtime_error(std::string("cpu info. unavailable"));
0035 }
0036
0037
0038 char readLine[1024];
0039 std::string searchString("cpu MHz");
0040 while ((cpuProcFile.rdstate() & std::ios::failbit) == 0)
0041 {
0042
0043
0044 cpuProcFile.getline(readLine, 1024);
0045 std::string readLineString(readLine);
0046 if (readLineString.find(searchString) != std::string::npos)
0047 {
0048
0049 size_t semicolonPosition = readLineString.find(':', 0);
0050 if (semicolonPosition == std::string::npos)
0051 {
0052 throw std::runtime_error(std::string("wrong format for cpu info file"));
0053 }
0054 std::string frequencyString(readLineString.substr(semicolonPosition + 1));
0055
0056
0057 double freqMHz = 0;
0058 std::istringstream frequencySstream(frequencyString);
0059
0060 frequencySstream >> freqMHz;
0061 _frequency = freqMHz * 1e6;
0062 }
0063 }
0064 }
0065
0066
0067 double PHTimer::get_difference(const PHTimer::time_struct& t0, const PHTimer::time_struct& t1)
0068 {
0069 unsigned long diff_high = t0._high - t1._high;
0070 unsigned long diff_low;
0071 if (t0._low < t1._low)
0072 {
0073 --diff_high;
0074 diff_low = (UINT_MAX - t1._low) + t0._low + 1;
0075 }
0076 else
0077 {
0078 diff_low = t0._low - t1._low;
0079 }
0080
0081 return (_twopower32 * diff_high + diff_low) * _frequency.period();
0082 }
0083
0084
0085 void PHTimer::PRINT(std::ostream& os, const std::string& message)
0086 {
0087 const int max_col = 80;
0088 if (message.empty())
0089 {
0090 os << std::string(max_col, '-') << std::endl;
0091 return;
0092 }
0093 int fill = max_col - message.size() - 2;
0094 int pre = static_cast<int>(std::floor(fill / 2.0));
0095 int post = fill - pre;
0096 os << std::string(pre, '-') << " ";
0097 os << message << " ";
0098 os << std::string(post, '-') << std::endl;
0099 }