add timeout to avoid unnecessarily high cpu usage.

This commit is contained in:
hecomi
2017-01-06 17:53:16 +09:00
parent 9ee2d35175
commit 06d4edbcb0
6 changed files with 51 additions and 6 deletions
@@ -62,3 +62,18 @@ void SendMessageToUnity(Message message)
{ {
g_messages.push(message); g_messages.push(message);
} }
ScopedTimer::ScopedTimer(TimerFuncType&& func)
: func_(func)
, start_(std::chrono::high_resolution_clock::now())
{
}
ScopedTimer::~ScopedTimer()
{
const auto end = std::chrono::high_resolution_clock::now();
const auto time = std::chrono::duration_cast<microseconds>(end - start_);
func_(time);
}
@@ -2,6 +2,7 @@
#include <functional> #include <functional>
#include <memory> #include <memory>
#include <chrono>
#include <wrl/client.h> #include <wrl/client.h>
@@ -32,7 +33,23 @@ public:
~ScopedReleaser() { func_(); } ~ScopedReleaser() { func_(); }
private: private:
ReleaseFuncType func_; const ReleaseFuncType func_;
};
// Timer
class ScopedTimer
{
public:
using microseconds = std::chrono::microseconds;
using TimerFuncType = std::function<void(microseconds)>;
ScopedTimer(TimerFuncType&& func);
~ScopedTimer();
private:
const TimerFuncType func_;
const std::chrono::time_point<std::chrono::steady_clock> start_;
}; };
@@ -1,5 +1,7 @@
#pragma once #pragma once
#include <chrono>
#include "Duplicator.h" #include "Duplicator.h"
#include "Monitor.h" #include "Monitor.h"
#include "MonitorManager.h" #include "MonitorManager.h"
@@ -139,12 +141,25 @@ void Duplicator::Start()
thread_ = std::thread([this] thread_ = std::thread([this]
{ {
using namespace std::chrono;
state_ = State::Running; state_ = State::Running;
shouldRun_ = true; shouldRun_ = true;
while (shouldRun_) while (shouldRun_)
{ {
if (!Duplicate()) break; const UINT timeout = 16 /* milliseconds */;
ScopedTimer timer([timeout] (microseconds us)
{
const auto waitTime = milliseconds(timeout) - us;
if (waitTime > microseconds::zero())
{
std::this_thread::sleep_for(waitTime);
}
});
if (!Duplicate(timeout)) break;
} }
if (state_ == State::Running) if (state_ == State::Running)
@@ -211,12 +226,10 @@ const Duplicator::Frame& Duplicator::GetLastFrame() const
} }
bool Duplicator::Duplicate() bool Duplicator::Duplicate(UINT timeout)
{ {
if (!dupl_ || !device_) return false; if (!dupl_ || !device_) return false;
const UINT timeout = 16;
ComPtr<IDXGIResource> resource; ComPtr<IDXGIResource> resource;
DXGI_OUTDUPL_FRAME_INFO frameInfo; DXGI_OUTDUPL_FRAME_INFO frameInfo;
const auto hr = dupl_->AcquireNextFrame(timeout, &frameInfo, &resource); const auto hr = dupl_->AcquireNextFrame(timeout, &frameInfo, &resource);
@@ -67,7 +67,7 @@ private:
void InitializeDuplication(); void InitializeDuplication();
void CheckUnityAdapter(); void CheckUnityAdapter();
bool Duplicate(); bool Duplicate(UINT timeout);
void UpdateCursor( void UpdateCursor(
const Microsoft::WRL::ComPtr<ID3D11Texture2D>& texture, const Microsoft::WRL::ComPtr<ID3D11Texture2D>& texture,