计算时间 c++

时间戳与计算程序运行时间


#include <chrono>
#include <iostream>
#include <random>

using namespace std;

inline float get_random_float(float min, float max) {
  std::random_device dev;
  std::mt19937 rng(dev());
  std::uniform_real_distribution<float> dist(min, max);
  return dist(rng);
}

inline int get_random_int(int min, int max) {
  std::random_device dev;
  std::mt19937 rng(dev());
  std::uniform_int_distribution<int> dist(min, max);
  return dist(rng);
}

int main(int, char**) {
  auto start = chrono::system_clock::now();
  cout << "开始时间" << start.time_since_epoch().count() << endl;
  
  int num = get_random_int(10, 20);
  cout << " 生成" << num << "个随机数" << endl;
  ;
  for (int i = 0; i < num; ++i) {
    cout << i << " : " << get_random_float(0.1f, 100.f) << endl;
  }
  
  auto end = chrono::system_clock::now();
  cout << "结束时间" << end.time_since_epoch().count() << endl;

  cout << "cost time " << chrono::duration_cast<chrono::hours>(end - start).count() << "(hours)" << endl;
  cout << "cost time" << chrono::duration_cast<chrono::minutes>(end - start).count() << "(minutes)" << endl;
  cout << "cost time" << chrono::duration_cast<chrono::seconds>(end - start).count() << "(seconds)" << endl;
  cout << "cost time" << chrono::duration_cast<chrono::milliseconds>(end - start).count() << "(milliseconds)" << endl;
  cout << "cost time" << chrono::duration_cast<chrono::microseconds>(end - start).count() << "(microseconds)" << endl;
}

程序运行结果

开始时间1630232790504861
 生成15个随机数
0 : 33.1166
1 : 89.589
2 : 58.1317
3 : 70.0451
4 : 97.3123
5 : 49.6868
6 : 24.3974
7 : 20.6575
8 : 24.9857
9 : 92.1825
10 : 91.3211
11 : 11.4127
12 : 11.7654
13 : 8.12993
14 : 18.8351
结束时间1630232790505445
cost time 0(hours)
cost time0(minutes)
cost time0(seconds)
cost time0(milliseconds)
cost time584(microseconds)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值