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
廣告