c语言获得当前时间戳
时间: 2025-01-30 15:41:45 浏览: 48
### 获取当前时间戳的方法
在C语言中,可以使用标准库函数来获取当前的时间戳。通常有两种常见的方式实现这一功能。
#### 使用 `time.h` 库中的 `time()` 函数
此方法返回自纪元以来的秒数(即1970年1月1日午夜UTC)。对于大多数应用来说已经足够精确[^1]:
```c
#include <stdio.h>
#include <time.h>
int main() {
time_t rawtime;
struct tm *info;
char buffer[80];
time(&rawtime);
printf("Current Timestamp (seconds since epoch): %ld\n", rawtime);
info = localtime(&rawtime);
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", info);
printf("Formatted Date and Time: %s\n", buffer);
return 0;
}
```
另一种更精确的方式来获得高精度的时间戳是通过 POSIX 扩展提供的 `gettimeofday()` 函数,在某些平台上可能不可用或已被弃用。如果需要更高的分辨率,则建议考虑使用 `<chrono>` 或者其他平台特定API[^2]:
```c
#ifdef _WIN32
#include <windows.h>
#else
#include <sys/time.h>
#endif
void printHighPrecisionTimestamp(){
#if defined(_WIN32)
FILETIME ft;
GetSystemTimeAsFileTime(&ft);
ULARGE_INTEGER ui;
ui.LowPart = ft.dwLowDateTime;
ui.HighPart = ft.dwHighDateTime;
// Convert from 100-nanosecond intervals to seconds.
uint64_t microseconds = (ui.QuadPart / 10ULL) - 11644473600000000ULL;
printf("Windows High Precision Timestamp: %" PRIu64 " us\n", microseconds);
#elif defined(__unix__) || defined(__APPLE__)
struct timeval tv;
gettimeofday(&tv,NULL);
uint64_t useconds = ((uint64_t)tv.tv_sec)*1000000 + tv.tv_usec;
printf("Unix/Apple High Precision Timestamp: %" PRIu64 " us\n",useconds );
#endif
}
```
阅读全文
相关推荐


















