#include <stdio.h>
#include <string.h>
#include <sys/time.h> // gettimeofday
#include <sys/timeb.h> // ftime
#include <time.h> // time clock_gettime
#include <unistd.h>
long get_system_time_nanosecond(); // 纳秒
long get_system_time_microsecond(); // 微秒
long get_system_time_millisecond(); // 毫秒
long get_system_time_second(); // 秒
long get_system_time_nanosecond()
{
struct timespec timestamp = {};
if (0 == clock_gettime(CLOCK_REALTIME, ×tamp))
return timestamp.tv_sec * 1000000000 + timestamp.tv_nsec;
else
return 0;
}
long get_system_time_microsecond()
{
struct timeval timestamp = {};
if (0 == gettimeofday(×tamp, NULL))
return timestamp.tv_sec * 1000000 + timestamp.tv_usec;
else
return 0;
}
long get_system_time_millisecond()
{
struct timeb timestamp = {};
if (0 == ftime(×tamp))
return timestamp.time * 1000 + timestamp.millitm;
else
return 0;
}
long get_system_time_second()
{
return time(NULL);
}
int main(int argc, char const *argv[])
{
long second = get_system_time_second();
long millisecond = get_system_time_millisecond();
long microsecond = get_system_time_microsecond();
long nanosecond = get_system_time_nanosecond();
printf("%ld\n", second);
printf("%ld\n", millisecond);
printf("%ld\n", microsecond);
printf("%ld\n", nanosecond);
return 0;
}
Linux C 获取系统时间秒/毫秒/微秒/纳秒
最新推荐文章于 2024-08-04 14:29:09 发布