1
2
3
4
5
6
7
| #include <time.h>
int clock_getres(clockid_t clk_id, struct timespec *res);
int clock_gettime(clockid_t clk_id, struct timespec *tp);
int clock_settime(clockid_t clk_id, const struct timespec *tp);
// Link with -lrt.
|
参数
- clk_id
- a、CLOCK_REALTIME:系统实时时间,随系统实时时间改变而改变
- b、CLOCK_MONOTONIC,从系统启动这一刻起开始计时,不受系统时间被用户改变的影响
- c、CLOCK_PROCESS_CPUTIME_ID,本进程到当前代码系统CPU花费的时间
- d、CLOCK_THREAD_CPUTIME_ID,本线程到当前代码系统CPU花费的时间
- tp
1
2
3
4
| struct timespec {
time_t tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};
|
示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| void oalTms_get(CmsTimestamp *tms)
{
struct timespec ts;
SINT32 rc;
if (tms == NULL)
{
return;
}
rc = clock_gettime(CLOCK_MONOTONIC, &ts);
if (rc == 0)
{
tms->sec = ts.tv_sec;
tms->nsec = ts.tv_nsec;
}
else
{
cwmp_log_error("clock_gettime failed, set timestamp to 0");
tms->sec = 0;
tms->nsec = 0;
}
}
|
问题
undefined reference to clock_gettime
发现是在链接的时候出错。经过查找发现clock_gettime在实时库librt(real time)里面,由于链接的时候没有链接这个库导致报错。
解决思路:
只需在我们运行的Makefile文件里面添加动态链接库librt ( -lrt ) ,重新编译即可。