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

记录一下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(&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;
}

代码执行结果:
在这里插入图片描述

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

  • 1
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值