程序占用cpu时间计算

程序占用cpu时间计算

源码

CMakeLists.txt

cmake_minimum_required(VERSION 3.5)

project(RunTimeCnt LANGUAGES CXX)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Os -std=c++11 -O3 -lpthread")
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

add_executable(RunTimeCnt main.cpp)
target_link_libraries(RunTimeCnt -lpthread)

main.cpp

#include <iostream>
#include <pthread.h>
#include <thread>
#include <chrono>
#include <sys/time.h>
#include <unistd.h>
#include <time.h>

using std::cout;
using std::endl;
using std::thread;
using std::this_thread::sleep_for;
using std::chrono::milliseconds;

// std::this_thread::sleep_for (std::chrono::milliseconds(1000));

class StopWatch{
private:
    struct timespec start_times;
    bool is_started;

public:
    void start() noexcept{
        clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &this->start_times);
        this->is_started = true;
    }
    unsigned long long int get_ns() noexcept{
        struct timespec end_times;
        //CLOCK_REALTIME:系统实时时间,随系统实时时间改变而改变,即从UTC1970-1-1 0:0:0开始计时,中间时刻如果系统时间被用户改成其他,则对应的时间相应改变。
        //CLOCK_MONOTONIC:从系统启动这一刻起开始计时,不受系统时间被用户改变的影响。
        //CLOCK_PROCESS_CPUTIME_ID:本进程到当前代码系统CPU花费的时间。
        //CLOCK_THREAD_CPUTIME_ID:本线程到当前代码系统CPU花费的时间。
        clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end_times); //

        unsigned long long int s = end_times.tv_sec - start_times.tv_sec;
        unsigned long long int ns = s * 1000000000UL + end_times.tv_nsec - start_times.tv_nsec;

        return ns;
    }

    double get_us() noexcept{
        return get_ns() / 1000.0;
    }

    double get_ms() noexcept{
        return get_ns() / 1000000.0;
    }
};

void Thread(){
    sleep_for(milliseconds(6000));

    cout << "thread exit!" << endl;
}

int main()
{
    StopWatch stop_watch;
    stop_watch.start();
    cout << "thread start!" << endl;
    thread t1{Thread};
    t1.join();
    cout << "ms: " << stop_watch.get_ms() << endl;
    cout << "us: " << stop_watch.get_us() << endl;
    cout << "ns: " << stop_watch.get_ns() << endl;
    return 0;
}

运行结果

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_Hello Spring

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值