在c/c++代碼中,有時(shí)需要實(shí)現(xiàn)計(jì)時(shí)功能,比如某個(gè)時(shí)刻開(kāi)始計(jì)時(shí),然后到另一時(shí)刻時(shí),計(jì)算距開(kāi)始計(jì)時(shí)的時(shí)刻毫秒數(shù)。
通過(guò)在起始時(shí)刻和停止時(shí)刻分別調(diào)用下面的代碼,返回的時(shí)間相減,便可獲得這段時(shí)間的毫秒數(shù),其跨Windows、Linux、VxWorks三個(gè)平臺(tái)。
#ifdef WIN32
#define OS_WINDOWS WIN32
#include <windows.h>
#endif
#ifdef LINUX
#include <unistd.h>
#include <sys/time.h>
#include <netinet/in.h>
#endif
#ifdef VXWORKS
#include "vxworks.h"
#include <tickLib.h>
#include <sysLib.h>
#endif
#define ULONAG unsigned long
ULONGA getTickCount(void)
{
ULONGA currentTime;
#ifdef WIN32
currentTime = GetTickCount();
#endif
#ifdef LINUX
struct timeval current;
gettimeofday(¤t, NULL);
currentTime = current.tv_sec * 1000 + current.tv_usec/1000;
#endif
#ifdef OS_VXWORKS
ULONGA timeSecond = tickGet() / sysClkRateGet();
ULONGA timeMilsec = tickGet() % sysClkRateGet() * 1000 / sysClkRateGet();
currentTime = timeSecond * 1000 + timeMilsec;
#endif
return currentTime;
}