1#pragma once
2
3#include <sys/time.h>
4
5#include "absl/strings/str_format.h"
6#include "muduo/base/ProcessInfo.h"
7#include "muduo/base/Timestamp.h"
8
9class Timer
10{
11 public:
12  Timer()
13    : start_(now()),
14      start_cpu_(muduo::ProcessInfo::cpuTime())
15  {
16  }
17
18  std::string report(int64_t bytes) const
19  {
20    muduo::ProcessInfo::CpuTime end_cpu(muduo::ProcessInfo::cpuTime());
21    double seconds = now() - start_;
22    char buf[64];
23    snprintf(buf, sizeof buf, "%'zd", bytes);
24    return absl::StrFormat("%.2fs real  %.2fs cpu  %6.2f MiB/s  %s bytes",
25                           seconds, end_cpu.total() - start_cpu_.total(),
26                           bytes / seconds / 1024 / 1024, buf);
27  }
28
29  static double now()
30  {
31    struct timeval tv = { 0, 0 };
32    gettimeofday(&tv, nullptr);
33    return tv.tv_sec + tv.tv_usec / 1000000.0;
34  }
35
36 private:
37  const double start_;
38  const muduo::ProcessInfo::CpuTime start_cpu_;
39};
40