C++在Windows下获取时间

我与影子孤独终老i 提交于 2020-01-06 17:06:29

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!