C 语言中获取时间有两种常用方法:time 函数返回自纪元以来经过的秒数。clock_gettime 函数返回当前时间,以指定时钟的秒数和纳秒数表示。

如何在 C 语言中获取时间
在 C 语言中获取时间有几种方法,最常用的有两种:
1. 使用 time 函数
time 函数返回自纪元(1970 年 1 月 1 日午夜)以来经过的秒数。其语法为:
立即学习“C语言免费学习笔记(深入)”;
<code class="c">time_t time(time_t *tloc);</code>
其中,tloc 参数是一个指向 time_t 变量的指针,用于存储返回的时间。
示例:
<code class="c">#include <time.h>
int main() {
time_t now;
time(&now);
printf("当前时间戳:%ld\n", now);
return 0;
}</code>2. 使用 clock_gettime 函数
clock_gettime 函数返回当前时间,以指定时钟的秒数和纳秒数表示。其语法为:
<code class="c">int clock_gettime(clockid_t clock_id, struct timespec *tp);</code>
其中:
- clock_id 指定要获取时间的时钟。CLOCK_REALTIME 通常用于获取系统时间。
- tp 指向一个 timespec 结构,用于存储返回的时间。
示例:
<code class="c">#include <time.h>
int main() {
struct timespec now;
clock_gettime(CLOCK_REALTIME, &now);
printf("当前时间戳:%ld\n", now.tv_sec);
printf("当前纳秒:%ld\n", now.tv_nsec);
return 0;
}</code>根据特定应用场景,选择合适的方法获取时间。time 函数返回以秒为单位的时间,而 clock_gettime 函数提供了更精细的时间(以纳秒为单位)。











