记录一下C/C++ 获取时间戳方法,毫秒级别
windows下:
#include <iostream>
#include <time.h>
#include<windows.h>
#include <stdint.h>
uint64_t GetCurrentTimerMS(char* szTimer=NULL)
{
uint64_t nTimer = 0;
SYSTEMTIME currentTime;
GetLocalTime(¤tTime);
tm temptm = { currentTime.wSecond,
currentTime.wMinute,
currentTime.wHour,
currentTime.wDay,
currentTime.wMonth - 1,
currentTime.wYear - 1900
};
nTimer = mktime(&temptm) * 1000 + currentTime.wMilliseconds;
if(szTimer != NULL)
sprintf(szTimer, "%llu", nTimer);
return nTimer;
}
int main(){
while(1)
{
char szTimer[64];
GetCurrentTimerMS(szTimer);
printf("millisecond:%s,\t%llu\n\n",szTimer,GetCurrentTimerMS()); //毫秒
Sleep(1);
}
return 0;
}
代码执行结果:
Linux下:
#include<iostream>
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>
int main(){
struct timeval tv;
while(1)
{
gettimeofday(&tv,NULL);
printf("millisecond:%ld\n\n",tv.tv_sec*1000 + tv.tv_usec/1000); //毫秒
usleep(900);
}
//gettimeofday(&tv,NULL);
//printf("millisecond:%ld\n",tv.tv_sec*1000 + tv.tv_usec/1000); //毫秒
//printf("microsecond:%ld\n",tv.tv_sec*1000000 + tv.tv_usec); //微秒
return 0;
}
如果想要写一个跨平台都能使用的话就增加一个宏定义判断:
#include <stdint.h>
#include <stdio.h>
#ifdef _WIN32
#include <time.h>
#include<windows.h>
#else
#include <sys/time.h>
#include <unistd.h>
#endif
uint64_t GetCurrentTimerMS(char* szTimer=NULL)
{
uint64_t nTimer = 0;
#ifdef _WIN32
SYSTEMTIME currentTime;
GetLocalTime(¤tTime);
tm temptm = { currentTime.wSecond,
currentTime.wMinute,
currentTime.wHour,
currentTime.wDay,
currentTime.wMonth - 1,
currentTime.wYear - 1900
};
nTimer = mktime(&temptm) * 1000 + currentTime.wMilliseconds;
#else
struct timeval tv;
gettimeofday(&tv,NULL);
// printf("second:%ld\n",tv.tv_sec); //秒
nTimer = tv.tv_sec*1000 + tv.tv_usec/1000;
#endif
if(szTimer != NULL)
sprintf(szTimer, "%llu", nTimer);
return nTimer;
}
int main()
{
char szTimer[64];
uint64_t nTimer=-1;
GetCurrentTimerMS(szTimer); //带参数
nTimer = GetCurrentTimerMS(); //不带参数
printf("millisecond:%s,\t%llu\n\n",szTimer,nTimer ); //毫秒
return 0;
}