linux下C语言获取微秒级时间

使用C语言在linux环境下获得微秒级时间

#include <sys/time.h>   
#include <unistd.h>
int gettimeofday(struct timeval*tv, struct timezone *tz);

函数说明:
gettimeofday()会把目前的时间有tv 所指的结构返回,当地时区的信息则放到tz 所指的结构中。时间是从公元 1970 年1 月1 日的UTC 时间从0 时0 分0 秒算起到现在所经过的时间。

其参数tv是保存获取时间结果的结构体,参数tz用于保存时区结果:

struct timezone{
int tz_minuteswest;/*格林威治时间往西方的时差*/
int tz_dsttime;/*DST 时间的修正方式*/
}

timezone 参数若不使用则传入NULL即可。

而结构体timeval的定义为:

struct timeval{
long int tv_sec; // 秒数
long int tv_usec; // 微秒数
}
#include <iostream>
#include <string>
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
using namespace std;
 
string fa_getSysTime()
{
     struct timeval tv;
     gettimeofday(&tv,NULL);
     struct tm* pTime;
     pTime = localtime(&tv.tv_sec);
        
     charsTemp[30] = {0};
     snprintf(sTemp, sizeof(sTemp), "%04d%02d%02d%02d%02d%02d%03d%03d", pTime->tm_year+1900, \
            pTime->tm_mon+1, pTime->tm_mday, pTime->tm_hour, pTime->tm_min, pTime->tm_sec, \
            tv.tv_usec/1000,tv.tv_usec%1000);
     return (string)sTemp;
}
 
int main()
{
   cout<< "当前时间:" << fa_getSysTime() << endl;
   return 0
}

另有usleep函数,time函数相对于gettimeofday就好比sleep函数相对usleep函数。

#include <unistd.h>
usleep(time);// 百万分之一秒
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容