---
title: clock_gettime
description: "获取纳秒级精度时间，CLOCK_REALTIME时钟源返回自1970年1月1日以来的秒数和纳秒数。该函数适用于获取高精度的时间戳。"
url: https://www.hikunpeng.com/document/detail/zh/kunpengboostkithistory/252RC1/accel/kunpengaccel_ksl_16_0211.html
sourcePath: /source/zh/kunpengboostkithistory/252RC1/accel/kunpengaccel_ksl_16_0211.html
indexId: 9c31ae4b7b8f0747887c90768ac104c9b189f003825f400906360332c56965c476
---
# clock_gettime

#### 函数功能

获取纳秒级精度时间，CLOCK_REALTIME时钟源返回自1970年1月1日以来的秒数和纳秒数。该函数适用于获取高精度的时间戳。


#### 函数定义

```
int clock_gettime(clockid_t clk_id,struct timespec *tp);
```


#### 参数说明

| 参数名 | 描述 | 取值范围 | 输入/输出 |
| --- | --- | --- | --- |
| clk\_id | 时钟源模式 | 目前仅优化支持CLOCK\_REALTIME | 输入 |
| tp | 指向struct timespec的指针，用于存储获取的时间值。 | 非空timespec结构体 | 输入/输出 |


#### 返回值

- 成功：返回0。
- 失败：若tp为空，返回KPGLIBC_STS_PARAMETER_ERR错误码。

clock_gettime提供的时间精度为纳秒级。


#### 示例

```
#include <stdio.h>
#include <time.h>
int main()
{
struct timespec ts;
if (clock_gettime(CLOCK_REALTIME, &ts) == -1) {
perror("clock_gettime error");
return 1;
}
printf("当前时间：%ld 秒 %ld 纳秒\n", ts.tv_sec, ts.tv_nsec);
return 0;
}
```

运行结果：

```
当前时间：***秒 ***纳秒
```
