C库 - time() 函数



C库的time()函数返回自纪元(UTC 1970年1月1日00:00:00)以来的秒数。如果seconds不为NULL,则返回值也会存储在变量seconds中。

在time()函数的上下文中,纪元确定时间戳值,即日期和时间。

语法

以下是C库time()函数的语法:

time_t time(time_t *t)

参数

此函数只接受单个参数:

  • seconds - 这是指向time_t类型对象的指针,秒数值将存储在此处。

返回值

此函数返回当前日历时间,作为一个time_t对象。

示例1

以下是一个基本的C库程序,用于演示time()函数。

#include <stdio.h>
#include <time.h>

int main () {
   time_t seconds;

   seconds = time(NULL);
   printf("Hours since January 1, 1970 = %ld\n", seconds/3600);
  
   return(0);
}

输出

以上代码产生以下结果:

Hours since January 1, 1970 = 393923

示例2

这里,我们使用time()函数以秒为单位测量时间值。

#include <stdio.h>
#include <time.h>

int main()
{
   time_t sec;
   // Store time in seconds
   time(&sec);
   printf("Seconds since January 1, 1970 = %ld\n", sec);
   return 0;
}

输出

执行上述代码后,我们将得到以下结果:

Seconds since January 1, 1970 = 1715856016

示例3

在这个例子中,我们使用time()函数以秒数的形式返回当前日历时间。因此,结果值最好作为Unix时间戳。

#include <stdio.h>
#include <time.h>

int main(void) {
    // Get the current time
    time_t now = time(NULL);

    printf("Current timestamp: %ld\n", now);

    // Convert to local time
    struct tm *local_time = localtime(&now);
    printf("Local time: %s", asctime(local_time));

    // Calculate a new time (add 1 minute)
    local_time -> tm_min += 1;
    time_t new_time = mktime(local_time);
    printf("New timestamp (1 minute later): %ld\n", new_time);

    // Format the time
    char formatted_time[100];
    strftime(formatted_time, sizeof(formatted_time), "%l %p", local_time);
    printf("Formatted time: %s\n", formatted_time);

    // Measure execution time
    clock_t start = clock();
    for (int i = 0; i < 100000000; ++i) { }
    clock_t end = clock();

    double total_time = (double)(end - start) / CLOCKS_PER_SEC;
    printf("Execution time: %.6f seconds\n", total_time);

    return 0;
}

输出

执行上述代码后,我们将得到以下结果:

Current timestamp: 1715853945
Local time: Thu May 16 10:05:45 2024
New timestamp (1 minute later): 1715854005
Formatted time: 10 AM
Execution time: 0.213975 seconds
广告
© . All rights reserved.