C++在Windows下获取时间
程序员文章站
2024-01-23 18:01:34
...
Windows下计算程序运行时间
Windows提供了获取CPU运算频率的函数QueryPerformanceFrequency(LARGE_INTEGER*)
以及获取当前CPU周期数的函数QueryPerformanceCounter(LARGE_INTEGER)
。所以更精确的时间计算方法就是求出CPU周期数的差值,除以运算频率,单位为秒。
LARGE_INTEGER freq = { 0 };
LARGE_INTEGER start = { 0 };
LARGE_INTEGER end = { 0 };
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&start);
Sleep(100);
QueryPerformanceCounter(&end);
std::cout << "frequency: " << freq.QuadPart << std::endl;
std::cout << "end - start: " << (end.QuadPart - start.QuadPart) << std::endl;
std::cout << "(end - start)/freq: "
<< ((double)(end.QuadPart - start.QuadPart)/(double)freq.QuadPart)
<< std::endl;
Windows下返回系统时间
为了与Java等其他语言对接,可以使用Windows SDK中的timeb.h
获取系统时间。并通过stringstream拼接出想要的毫秒数,下面的方法得到的8个字节的无符号整数就是当前系统时间到1970年1月1日0点的毫秒数。
#include <sys/timeb.h>
#include <ctime>
#include <string>
#include <sstream>
#include <iostream>
#include <iomanip>
UINT64 getCurrentTimeMillis()
{
using namespace std;
timeb now;
ftime(&now);
std::stringstream milliStream;
milliStream << setw(3) << setfill('0') << right << now.millitm;
stringstream secStream;
secStream << now.time;
string timeStr(secStream.str());
timeStr.append(milliStream.str());
UINT64 timeLong;
stringstream transStream(timeStr);
transStream >> timeLong;
return timeLong;
}