このブログを検索

2019年4月8日月曜日

【C++】 時間の計測

【C++】 時間の計測
(2019年4月8日)


■使用ソフト
・Visual Studio Community 2019


■言語
・C/C++


■Windows SDK バージョン
・10.0.17763.0
 ※Windows SDK バージョンの変更方法


■手順

以下の3種類の方法を記載

timeGetTime
std::chrono
QueryPerformanceCounter


<timeGetTime>

1.基本的には以下の流れ参照
【C++】 メッセージボックスの作成

2.C++ファイル(.cpp)を以下のとおり変更する。

#pragma comment(lib,"winmm.lib")
#include <windows.h>
#include <wchar.h>

int WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow)
{
    DWORD Before, After;
    WCHAR wcText[256];

    timeBeginPeriod(1);
    Before = timeGetTime();
    Sleep(1000);
    After = timeGetTime();

    swprintf(wcText, 256, L"%lu", After - Before);

    MessageBox(NULL, wcText, L"時間の計測", MB_OK);

    timeEndPeriod(1);
    return 0;
}

※timeGetTime()を使用するために#pragma comment(lib,"winmm.lib")が必要

3.BeforeからAfterまでの処理にかかった時間が表示される。


<std::chrono>

1.基本的には以下の流れ参照
【C++】 メッセージボックスの作成

2.C++ファイル(.cpp)を以下のとおり変更する。

#include <windows.h>
#include <wchar.h>
#include <chrono>

int WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow)
{
    WCHAR wcText[256];

    auto Before = std::chrono::system_clock::now();
    Sleep(1000);
    auto After = std::chrono::system_clock::now();
    auto Calc = After - Before;
    auto Time = std::chrono::duration_cast<std::chrono::milliseconds>(Calc).count();

    swprintf(wcText, 256, L"%lld", Time);

    MessageBox(NULL, wcText, L"時間の計測", MB_OK);

    return 0;
}

※std::chronoを使用するために#include <chrono>が必要

3.BeforeからAfterまでの処理にかかった時間が表示される。


<QueryPerformanceCounter>

1.基本的には以下の流れ参照
【C++】 メッセージボックスの作成

2.C++ファイル(.cpp)を以下のとおり変更する。

#include <windows.h>
#include <wchar.h>

int WINAPI wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow)
{
    LARGE_INTEGER Freq = { 0 };
    LARGE_INTEGER Before = { 0 };
    LARGE_INTEGER After = { 0 };
    long long Time;
    WCHAR wcText[256];

    QueryPerformanceFrequency(&Freq);
    QueryPerformanceCounter(&Before);
    Sleep(1000);
    QueryPerformanceCounter(&After);

    Time = (After.QuadPart - Before.QuadPart) * 1000 / Freq.QuadPart;

    swprintf(wcText, 256, L"%lld", Time);

    MessageBox(NULL, wcText, L"時間の計測", MB_OK);

    return 0;
}

3.BeforeからAfterまでの処理にかかった時間が表示される。

0 件のコメント:

コメントを投稿