1. 思路
我们在执行函数前后分别记录下时间戳,然后计算两个时间戳的差值即可。
我们需要借助函数clock_gettime来实现这个功能。看下该函数的定义:
- #include <time.h>
- int clock_gettime(clockid_t clk_id, struct timespec* tp);
- 可以根据需要,获取不同要求的精确时间
- 参数:
- clk_id :
- 检索和设置的clk_id指定的时钟时间。
- CLOCK_REALTIME:系统实时时间,随系统实时时间改变而改变,即从UTC1970-1-1 0:0:0开始计时,中间时刻如果系统时间被用户改成其他,则对应的时间相应改变
- CLOCK_MONOTONIC:从系统启动这一刻起开始计时,不受系统时间被用户改变的影响
- CLOCK_PROCESS_CPUTIME_ID:本进程到当前代码系统CPU花费的时间
- CLOCK_THREAD_CPUTIME_ID:本线程到当前代码系统CPU花费的时间
- tp :
- 获取的时间戳会存放到该结构体变量中
- struct timespec
- {
- time_t tv_sec; /* 秒*/
- long tv_nsec; /* 纳秒*/
- };
- 返回值:
- 成功 0
- 失败 -1 ,同时errno会被赋值
因为我们希望计算执行某个函数的时间,所以我们第一个参数选择CLOCK_MONOTONIC。
2. 实例1
我们先来实现一个简单的程序:
- 1 #include <stdio.h>
- 2 #include <stdlib.h>
- 3 #include <stdint.h>
- 4 #include <time.h>
- 5 #include <sys/time.h>
- 6 #include <sys/stat.h>
- 7 #include <sys/types.h>
- 8 #include <unistd.h>
- 9 #include <string.h>
- 10
- 11 int main()
- 12 {
- 13 int rc;
- 14 struct timespec ts_start, ts_end;
- 15
- 16 //start time before call function
- 17 rc = clock_gettime(CLOCK_MONOTONIC, &ts_start);
- 18
- 19 printf("you can call your function here\n");
- 20
- 21 //end time before call function
- 22 rc = clock_gettime(CLOCK_MONOTONIC, &ts_end);
- 23
- 24 printf("CLOCK_MONOTONIC reports %ld.%09ld seconds\n",
- 25 ts_end.tv_sec – ts_start.tv_sec, ts_end.tv_nsec – ts_start.tv_nsec);
- 26 }
19行 我们可以将自己要执行的函数放置在此处。
编译
- gcc runtime.c -lrt
注意需要增加动态链接库lrt,函数clock_gettime()定义于该库中。
执行结果如下:
- root@ubuntu:/home/peng/zhh# ./a.out
- you can call your function here
- CLOCK_MONOTONIC reports 0.000013689 seconds