c++获取当前秒 毫秒 微秒 纳秒时间

c++获取当前秒 毫秒 微秒 纳秒时间,便于算法运行时间比较。

// 获取当前时间的时间戳
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <chrono>
#include <thread>

int main()
{
    auto currentTime = std::chrono::system_clock::now();
    auto currentTime_s = std::chrono::time_point_cast<std::chrono::seconds>(currentTime);
    auto currentTime_ms = std::chrono::time_point_cast<std::chrono::milliseconds>(currentTime);
    auto currentTime_micro = std::chrono::time_point_cast<std::chrono::microseconds>(currentTime);
    auto currentTime_ns = std::chrono::time_point_cast<std::chrono::nanoseconds>(currentTime);
    auto valueS = currentTime_s.time_since_epoch().count();
    auto valueMS = currentTime_ms.time_since_epoch().count();
    auto valueMicroS = currentTime_micro.time_since_epoch().count();
    auto valueNS = currentTime_ns.time_since_epoch().count();

    std::cout << "Seconds: " << valueS << std::endl;
    std::cout << "Milliseconds: " << valueMS << std::endl;
    std::cout << "Microseconds: " << valueMicroS << std::endl;
    std::cout << "Nanoseconds: " << valueNS << std::endl;

    //std::cout << "time_s_mils_mics: " << valueS << "  " << valueMS << "  " << valueMicroS << std::endl;

    return 0;
}

注意:

  • steady_clock 是单调的时钟,相当于教练手中的秒表;只会增长,适合用于记录程序耗时
  • system_clock 是系统的时钟;因为系统的时钟可以修改;甚至可以网络对时; 所以用系统时间计算时间差可能不准。
  • high_resolution_clock 是当前系统能够提供的最高精度的时钟;它也是不可以修改的。相当于 steady_clock
    的高精度版本。
//如果延时、计时用此函数
#include <iostream>
#include <chrono>

int main() {
    // 获取当前时间
    // 转换为毫秒精度
    // 获取时间戳
    auto now = std::chrono::steady_clock::now();
    auto now_ms = std::chrono::time_point_cast<std::chrono::milliseconds>(now);
    auto ms = now_ms.time_since_epoch().count();

    std::cout << "当前时间(毫秒精度): " << ms << " 毫秒" << std::endl;

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值