我正在嘗試在我的程序中使用「rusage」統計來獲取與time工具類似的數據。但是,我很確定我做錯了什麼。這些價值似乎是正確的,但有時可能有點奇怪。我沒有在網上找到好的資源。有人知道如何做得更好嗎?「rusage」統計
對不起,長碼。
class StopWatch {
public:
void start() {
getrusage(RUSAGE_SELF, &m_begin);
gettimeofday(&m_tmbegin, 0);
}
void stop() {
getrusage(RUSAGE_SELF, &m_end);
gettimeofday(&m_tmend, 0);
timeval_sub(m_end.ru_utime, m_begin.ru_utime, m_diff.ru_utime);
timeval_sub(m_end.ru_stime, m_begin.ru_stime, m_diff.ru_stime);
timeval_sub(m_tmend, m_tmbegin, m_tmdiff);
}
void printf(std::ostream& out) const {
using namespace std;
timeval const& utime = m_diff.ru_utime;
timeval const& stime = m_diff.ru_stime;
format_time(out, utime);
out << "u ";
format_time(out, stime);
out << "s ";
format_time(out, m_tmdiff);
}
private:
rusage m_begin;
rusage m_end;
rusage m_diff;
timeval m_tmbegin;
timeval m_tmend;
timeval m_tmdiff;
static void timeval_add(timeval const& a, timeval const& b, timeval& ret) {
ret.tv_usec = a.tv_usec + b.tv_usec;
ret.tv_sec = a.tv_sec + b.tv_sec;
if (ret.tv_usec > 999999) {
ret.tv_usec -= 1000000;
++ret.tv_sec;
}
}
static void timeval_sub(timeval const& a, timeval const& b, timeval& ret) {
ret.tv_usec = a.tv_usec - b.tv_usec;
ret.tv_sec = a.tv_sec - b.tv_sec;
if (a.tv_usec < b.tv_usec) {
ret.tv_usec += 1000000;
--ret.tv_sec;
}
}
static void format_time(std::ostream& out, timeval const& tv) {
using namespace std;
long usec = tv.tv_usec;
while (usec >= 1000)
usec /= 10;
out << tv.tv_sec << '.' << setw(3) << setfill('0') << usec;
}
}; // class StopWatch
我不確定你的意思是不同的usec位數。據我所知,其中的所有值都是在0到999,999之間,分別對應0 ms和999.999 ms。 「最重要的三位數字」對我來說意味着你想要毫秒數。我看錯了嗎? – 2008-09-18 10:24:38