在Linux系统中,获取当前时间的微秒级精度可以通过多种方法实现。以下是一些常用的方法和示例代码:
gettimeofday
函数gettimeofday
函数可以获取当前时间的秒数和微秒数。
#include <sys/time.h>
#include <stdio.h>
int main() {
struct timeval tv;
gettimeofday(&tv, NULL);
long micros = tv.tv_usec;
long seconds = tv.tv_sec;
printf("Current time: %ld seconds and %ld microseconds
", seconds, micros);
return 0;
}
clock_gettime
函数clock_gettime
函数可以获取高精度的时间,使用CLOCK_REALTIME
或CLOCK_MONOTONIC
时钟。
#include <time.h>
#include <stdio.h>
int main() {
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
long micros = ts.tv_nsec / 1000; // 将纳秒转换为微秒
long seconds = ts.tv_sec;
printf("Current time: %ld seconds and %ld microseconds
", seconds, micros);
return 0;
}
std::chrono
库(C++)在C++中,可以使用std::chrono
库来获取高精度时间。
#include <iostream>
#include <chrono>
int main() {
auto now = std::chrono::high_resolution_clock::now();
auto micros = std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch()).count();
std::cout << "Current time in microseconds since epoch: " << micros << "
";
return 0;
}
gettimeofday
和clock_gettime
在大多数Unix-like系统上都可用,而std::chrono
是C++标准库的一部分,具有良好的跨平台性。通过以上方法,你可以在Linux系统中获取当前时间的微秒级精度,并根据具体需求选择合适的方法。
领取专属 10元无门槛券
手把手带您无忧上云