C/C++ 获取时间戳(毫秒级别)

记录一下C/C++ 获取时间戳方法,毫秒级别

windows下:

#include 
#include 
#include
#include 

uint64_t GetCurrentTimerMS(char* szTimer=NULL)
{
	uint64_t nTimer = 0;
	SYSTEMTIME currentTime;
	GetLocalTime(&currentTime);

	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;
}

代码执行结果:
C/C++ 获取时间戳(毫秒级别)_第1张图片

Linux下:

#include
#include 
#include 
#include 
#include 
 
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 
#include 
#ifdef _WIN32
    #include 
    #include
#else
    #include 
    #include 
#endif

uint64_t GetCurrentTimerMS(char* szTimer=NULL)
{
    uint64_t nTimer = 0;
#ifdef _WIN32
	SYSTEMTIME currentTime;
	GetLocalTime(&currentTime);
	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;
}

你可能感兴趣的:(C/C++,ubuntu,c++)