ICode9

精准搜索请尝试: 精确搜索
首页 > 系统相关> 文章详细

linux 获取程序执行时间的方法

2021-04-11 21:31:36  阅读:172  来源: 互联网

标签:end start clock per 程序执行 获取 ms linux 1000


code:

#include <stdio.h>
#include <stdarg.h>
#include <unistd.h>/*for sleep*/
#include <sys/times.h>/*for times*/
#include <sys/time.h>/*for getimeofday*/
//#include <sys/conf.h>/*old system for sysconf*/
#include <time.h>/*for clock,time,clock_gettime*/


void demo_time01()
{
    time_t start =time(NULL);//获取系统时间,只精确到秒,不能反映程序真正的运行时间
    long i =0;
    while(i<10e8)
    {
        i++;
    }
    time_t end=time(NULL);
    printf("执行时间:%ld s\n",end - start);
}

void demo_time02()
{
    struct timeval start;
    struct timeval end;
    gettimeofday(&start,NULL);

    long i = 0;

    while(i<10e8)
    {
        i++;
    }
    gettimeofday(&end,NULL);

    long start_ms=start.tv_sec*1000+start.tv_usec/1000;
    long end_ms=end.tv_sec*1000+end.tv_usec/1000;

    printf("执行时间:%ld ms\n",end_ms - start_ms);   

}

void demo_time03()
{
    struct tms t;
    long i = 0;

    while(i<10e6)
    {
        i++;
    }
    times(&t);
    long clock_per_sec=sysconf(_SC_CLK_TCK);
    double clock_per_ms = (double)clock_per_sec/1000;
    printf("用户空间时间:%.4lf 内核空间时间:%.4lf\n",
        t.tms_utime/clock_per_ms,
        t.tms_stime/clock_per_ms
    ); 


}
void demo_time04()
{
    long i = 0;
    while(i<10e6)
    {
        i++;
    }
    clock_t ticks=clock();//32bit最多记录72min,从进程开始就开始记录,不能控制
    double secs=(double)ticks/CLOCKS_PER_SEC;//us
    printf("执行时间:%.4lf ms\n", secs*1000);

}

void demo_time05()
{

    struct timespec start;//精确到纳秒,CLOCK_PROCESS_CPUTIME_ID能反映出程序真正的运行时间,方便控制
    struct timespec end;
    
    clock_gettime(CLOCK_PROCESS_CPUTIME_ID,&start);
    long i = 0;
    while(i<10e8)//10e6 17ms, 10e8 1700ms 测试耗时为大概时间
    {
        i++;
    }

    clock_gettime(CLOCK_PROCESS_CPUTIME_ID,&end);
    double start_ms =start.tv_sec*1000+start.tv_nsec/1000000;//转为毫秒
    double end_ms =end.tv_sec*1000+end.tv_nsec/1000000;

    printf("clock_gettime执行时间:%.4lf ms\n",end_ms - start_ms);
}

int main()
{

    struct tms t;
    demo_time04();//从进入main函数开始计时,不在前面执行会记录到其他函数的时间
    demo_time01();
    demo_time05();

    times(&t);
    long clock_per_sec=sysconf(_SC_CLK_TCK);
    double clock_per_ms = (double)clock_per_sec/1000;
    printf("用户空间时间:%.4lfms 内核空间时间:%.4lfms \n",
        t.tms_utime/clock_per_ms,
        t.tms_stime/clock_per_ms
    ); 

    return 0;
}

标签:end,start,clock,per,程序执行,获取,ms,linux,1000
来源: https://blog.csdn.net/weixin_42244181/article/details/115606979

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有