linux timestamp

驱动或应用中获取时间戳的接口。

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <time.h>

#include <sys/time.h>

#if 0

#include <linux/ktime.h>

/* 内核驱动中获取时间戳 */

static ktime_t get_kernel_timestamp(void)

{

ktime_t ktime = ktime_get(); // 获取当前时间

u64 timestamp = ktime_to_ns(ktime); // 将ktime转换为纳秒时间戳

printk(KERN_INFO "Current timestamp: %llu nanoseconds\n", timestamp);

return ktime;

}

#endif

int convert_utc_time( unsigned long long utc, char * ptime)

{

struct tm *tm;

time_t t = 0;

if (utc == 0) {

strncpy(ptime, "no time", 8);

return -1;

}

t = utc / 1000 + 8 * 3600;

tm = gmtime(&t);

sprintf(ptime, "%04d:%02d:%02d %02d:%02d:%02d.%03d", tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,

tm->tm_hour, tm->tm_min, tm->tm_sec, (int)utc%1000);

printf("utc time for ac debug : [%s]\n", ptime);

return 0;

}

static unsigned long long GetSystemClock_ns()

{

struct timespec time_start, time_end;

clock_gettime(CLOCK_REALTIME, &time_start);

return (long long unsigned)time_start.tv_sec * 1000000000 + (long long unsigned)time_start.tv_nsec;

}

static inline struct timeval AC_TIME_COMMON_GetMonotonic()

{

struct timespec stTime;

struct timeval stRet;

clock_gettime(CLOCK_REALTIME, &stTime);

stRet.tv_sec = stTime.tv_sec - timezone;

stRet.tv_usec = stTime.tv_nsec/1000;

return stRet;

}

static unsigned long long GetSystemClock()

{

struct timeval tv;

unsigned long long tv_sen;

unsigned long long gltime;

gettimeofday(&tv, NULL);

tv_sen = tv.tv_sec;

gltime = tv_sen * 1000 + tv.tv_usec / 1000;

return gltime;

}

int main()

{

char u_time[32] = {0};

unsigned long long system_time = 0;

struct timeval tmData = AC_TIME_COMMON_GetMonotonic();

system_time = tmData.tv_sec*1000 + tmData.tv_usec / 1000;

printf("get time %lld\n", system_time); // 1655445920614 : 2022:06:17 14:05:20.654

system_time = 0;

system_time = GetSystemClock();

printf("get time %lld\n", system_time); // 1655446828225 : 2022:06:17 14:20:28.265

system_time = 0;

system_time = GetSystemClock_ns(); // 1721875113493839086

printf("get time %lld\n", system_time);

convert_utc_time(1655356228, u_time);

convert_utc_time(1823430235, u_time);

convert_utc_time(1918628771, u_time);

convert_utc_time(1655445920614, u_time); // 2022:06:17 14:05:20.654

convert_utc_time(1655446828225, u_time); // 2022:06:17 14:20:28.265

}

相关推荐
无限进步_30 分钟前
【Linux】gcc/g++ 编译:从源码到可执行文件的四个阶段
linux·运维·服务器
原来是猿9 小时前
网络计算器:理解序列化与反序列化(中)
linux·运维·服务器·网络·tcp/ip
AOwhisky10 小时前
虚拟化技术学习笔记
linux·运维·笔记·学习·虚拟化技术
rabbit_pro11 小时前
Docker compose部署Ollama使用模型
linux·运维·docker
Irissgwe13 小时前
六、Ext系列文件系统(2.核心原理与应用)
linux·分区··inode·软硬连接·路径缓存·ext系列文件
tkevinjd13 小时前
wsl2安装
linux·wsl·虚拟机·wsl2
故事还在继续吗13 小时前
Linux 内核模块开发实战
linux·linux内核
南境十里·墨染春水14 小时前
linux学习进展 守护进程
linux·服务器·学习
REDcker14 小时前
Android HWASan 详解:硬件标记原理、Clang 启用与排障实践
android·linux·debug·编译·clang·asan·hwasan
数智工坊15 小时前
VMware 17 Pro 中 Ubuntu 虚拟机共享 Windows 文件夹(完美踩坑版)
linux·人工智能·windows·ubuntu