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

2021/4/12 7:28:00

本文主要是介绍linux 获取程序执行时间的方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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;
}


这篇关于linux 获取程序执行时间的方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程