C/C++ 时间处理

#include <ctime>
#include <string>
#include <iostream>

std::string get_greet(const std::string& who) {
  return "Hello " + who;
}

void print_localtime() {
  std::time_t result = std::time(nullptr);
  std::cout << result << std::endl;
  std::cout << std::localtime(&result) << std::endl;
  std::cout << std::asctime(std::localtime(&result));
}

int main(int argc, char** argv) {
  std::string who = "world";
  if (argc > 1) {
    who = argv[1];
  }
  std::cout << get_greet(who) << std::endl;
  print_localtime();
  return 0;
}

Hello world
1569459184
0x7fea17500180
Thu Sep 26 08:53:04 2019

#include <iostream>
#include <sys/time.h>
#include <unistd.h>
#include <cmath>
using namespace std;
class Timer {
public:
  Timer() { Reset(); }
  explicit Timer(bool set_timer) { if (set_timer) Reset(); }
  void Reset() { gettimeofday(&this->time_start_, &time_zone_); }
  double Elapsed() const {
  struct timeval time_end;
  struct timezone time_zone;
  gettimeofday(&time_end, &time_zone);
  double t1, t2;
  t1 =  static_cast<double>(time_start_.tv_sec) +
    	  static_cast<double>(time_start_.tv_usec)/(1000*1000);
  t2 =  static_cast<double>(time_end.tv_sec) +
    	  static_cast<double>(time_end.tv_usec)/(1000*1000);
    return t2-t1;
  }

private:
  struct timeval time_start_;
  struct timezone time_zone_;
};

void Sleep(float seconds){
	usleep(static_cast<int>(seconds * 1000000.0));
}

void TimerTest(){
  float time_secs = 0.025 * (rand() % 10);
  std::cout << "target is " << time_secs << "\n";
  Timer timer;
  Sleep(time_secs);
  float f = timer.Elapsed();
  std::cout << "time is " << f << " " << fabs(time_secs - f) << std::endl;

  if (fabs(time_secs - f) > 0.05)
    cout << "Timer fail: waited " << f << " seconds instead of "
              <<  time_secs << " secs.";
}

int main() {
  for (int i = 0; i < 5; i++)
    TimerTest();
  return 0;
}

target is 0.075
time is 0.0751109 0.000110909
target is 0.15
time is 0.15011 0.00011
target is 0.175
time is 0.175105 0.000105098
target is 0.125
time is 0.125109 0.000108957
target is 0.075
time is 0.075103 0.000103042

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值