HRESULT __stdcall CStopwatchClassFactory::CreateInstance(IUnknown *pUnkOuter, REFIID riid, void **ppvObject) { HRESULT hr; CStopwatch* pStopwatch = new CStopwatch; hr = pStopwatch->QueryInterface(riid, ppvObject); if (FAILED(hr)) { delete pStopwatch; } return hr; }
bool CCondVarBase::wait(CStopwatch& timer, double timeout) const { // check timeout against timer if (timeout >= 0.0) { timeout -= timer.getTime(); if (timeout < 0.0) return false; } return wait(timeout); }
void BaseApp::Run() { CStopwatch timer; int sum = 0; int counter = 0; int deltaTime = 0; while (1) { timer.Start(); if (kbhit()) { KeyPressed (getch()); if (!FlushConsoleInputBuffer(mConsoleIn)) cout<<"FlushConsoleInputBuffer failed with error "<<GetLastError(); } UpdateF((float)deltaTime / 1000.0f); Render(); Sleep(1); while (1) { deltaTime = timer.Now(); if (deltaTime > 20) break; } sum += deltaTime; counter++; if (sum >= 1000) { TCHAR szbuff[255]; StringCchPrintf(szbuff, 255, TEXT("FPS: %d"), counter); SetConsoleTitle(szbuff); counter = 0; sum = 0; } } }
void MeasureConcurrentOperation( TCHAR* operationName, DWORD nThreads, OPERATIONFUNC operationFunc) { HANDLE* phThreads = new HANDLE[nThreads]; SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST); for (DWORD currentThread = 0; currentThread < nThreads; currentThread++) { phThreads[currentThread] = CreateThread(NULL, 0, ThreadIterationFunction, operationFunc, 0, NULL); } SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL); CStopwatch watch; WaitForMultipleObjects(nThreads, phThreads, TRUE, INFINITE); __int64 elapsedTime = watch.Now(); _tprintf( TEXT("Threads=%u, Milliseconds=%u, Test=%s\n"), nThreads, (DWORD)elapsedTime, operationName); // Don't forget to clean up the thread handles for (DWORD currentThread = 0; currentThread < nThreads; currentThread++) { CloseHandle(phThreads[currentThread]); } delete phThreads; }
bool GLoadToken::LoadBuffer(const TCHAR* strFileName) { CStopwatch stopwatch; TCHAR Drive[MAX_PATH]; TCHAR Dir[MAX_PATH]; TCHAR FName[MAX_PATH]; TCHAR Ext[MAX_PATH]; _tsplitpath(strFileName, Drive, Dir, FName, Ext); m_szDirName = Drive; m_szDirName += Dir; m_szName = FName; m_szName += Ext; LARGE_INTEGER FileSize; m_hHandle = CreateFile(strFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (m_hHandle != INVALID_HANDLE_VALUE) { GetFileSizeEx(m_hHandle, &FileSize); UINT cBytes = FileSize.LowPart; SAFE_NEW_ARRAY(m_pmbStaticMeshData, char, cBytes); if (!m_pmbStaticMeshData) { DeleteBuffer(); return false;//E_OUTOFMEMORY; } DWORD dwBytesRead; if (!ReadFile(m_hHandle, m_pmbStaticMeshData, cBytes, &dwBytesRead, NULL)) { DeleteBuffer(); return false; } //SetFilePointer( m_hHandle, 0, 0, FILE_BEGIN ); } else { return false; } TCHAR* szMeshData = NULL; TCHAR* SearchString = NULL; size_t convertedChars = 0; SAFE_NEW_ARRAY(m_pwcStaticMeshData, TCHAR, FileSize.LowPart); if (mbstowcs_s(&convertedChars, m_pwcStaticMeshData, FileSize.LowPart, m_pmbStaticMeshData, _TRUNCATE) == 0) { DeleteBuffer(); return false; } if (m_pwcStaticMeshData) { SAFE_DELETE_ARRAY(m_pmbStaticMeshData); m_pwcTokenData = m_pwcStaticMeshData; m_pwcSearchData = m_pwcStaticMeshData; } CloseHandle(m_hHandle); m_hHandle = 0; BeginToken(); stopwatch.Output(L"GLoadToken::LoadBuffer"); return true; }
void CEngine::RunGameLoop() { // Enter the message loop MSG msg; ZeroMemory(&msg, sizeof(msg)); #ifdef USE_DISP_FPS char text[256] = {"\0"}; #endif while (msg.message != WM_QUIT) { if (PeekMessage(&msg, nullptr, 0U, 0U, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } else { #ifdef USE_DISP_FPS CStopwatch sw; sw.Start(); #endif GameTime().Update(); //キー入力を更新。 m_keyInput.Update(); m_skinModelDataResources.Update(); m_physicsWorld.Update(); CRenderContext& topRenderContext = m_renderContextArray[0]; CRenderContext& lastRenderContext = m_renderContextArray[m_numRenderContext - 1]; topRenderContext.SetRenderTarget(0, &m_mainRenderTarget[m_currentMainRenderTarget]); //topRenderContext.SetRenderTarget(0, &m_backBufferRT); topRenderContext.SetRenderTarget(1, NULL); CGameObjectManager& goMgr = CGameObjectManager::Instance(); goMgr.Execute( m_renderContextArray.get(), m_numRenderContext, m_renderContextMap.get(), m_preRender, m_postEffect ); lastRenderContext.SetRenderTarget(0, &m_backBufferRT); lastRenderContext.Clear(0, nullptr, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_RGBA(0, 0, 0, 0), 1.0f, 0 ); CopyMainRenderTargetToBackBuffer(lastRenderContext); m_pD3DDevice->BeginScene(); //レンダリングコマンドのサブミット for( int i = 0; i < m_numRenderContext; i++ ){ m_renderContextArray[i].SubmitCommandBuffer(); } // 描画 #ifdef USE_DISP_FPS m_fpsFont.Draw(text, 0, 0); #endif m_pD3DDevice->EndScene(); m_pD3DDevice->Present(nullptr, nullptr, nullptr, nullptr); // #ifdef USE_DISP_FPS sw.Stop(); sprintf(text, "fps = %lf\n", 1.0f / sw.GetElapsed()); #endif } } }
bool GGbsModel::Init(TCHAR* strFileName, TCHAR* strShaderName) { HRESULT hr = S_OK; //파싱, 필요한 처리 시작. CStopwatch stopwatch; //I_AseParser I_GbsParser.InitGbsModel(strFileName, this); //필요한 처리 끝. stopwatch.Output(L"Init()"); // Create the sample state D3D11_SAMPLER_DESC sampDesc; ZeroMemory(&sampDesc, sizeof(sampDesc)); sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; sampDesc.MinLOD = 0; sampDesc.MaxLOD = D3D11_FLOAT32_MAX; hr = g_pd3dDevice->CreateSamplerState(&sampDesc, m_pSamplerLinear.GetAddressOf()); if (FAILED(hr)) return hr; // Compile the vertex shader ID3DBlob* pVSBlob = NULL; hr = CompileShaderFromFile(strShaderName, "VS", "vs_4_0", &pVSBlob); if (FAILED(hr)) { MessageBox(NULL, L"The FX file cannot be compiled. Please run this executable from the directory that contains the FX file.", L"Error", MB_OK); return hr; } // Create the vertex shader hr = g_pd3dDevice->CreateVertexShader(pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), NULL, m_pVertexShader.GetAddressOf()); if (FAILED(hr)) { pVSBlob->Release(); return hr; } // Define the input layout D3D11_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 40, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; UINT numElements = ARRAYSIZE(layout); // Create the input layout hr = g_pd3dDevice->CreateInputLayout(layout, numElements, pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), m_pVertexLayout.GetAddressOf()); pVSBlob->Release(); if (FAILED(hr)) return hr; // Set the input layout g_pImmediateContext->IASetInputLayout(m_pVertexLayout.Get()); // Compile the pixel shader ID3DBlob* pPSBlob = NULL; hr = CompileShaderFromFile(strShaderName, "PS", "ps_4_0", &pPSBlob); if (FAILED(hr)) { MessageBox(NULL, L"The FX file cannot be compiled. Please run this executable from the directory that contains the FX file.", L"Error", MB_OK); return hr; } // Create the pixel shader hr = g_pd3dDevice->CreatePixelShader(pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(), NULL, m_pPixelShader.GetAddressOf()); pPSBlob->Release(); if (FAILED(hr)) return hr; if (m_vGeomObj.size() == 1) SingleModelInit(); else MultiModelInit(); return true; };
void CFileChunker::sendFileChunks(char* filename, IEventQueue* events, void* eventTarget) { std::fstream file(reinterpret_cast<char*>(filename), std::ios::in | std::ios::binary); if (!file.is_open()) { throw runtime_error("failed to open file"); } // check file size file.seekg (0, std::ios::end); size_t size = (size_t)file.tellg(); // send first message (file size) CString fileSize = intToString(size); size_t sizeLength = fileSize.size(); CFileChunk* sizeMessage = new CFileChunk(sizeLength + 2); char* chunkData = sizeMessage->m_chunk; chunkData[0] = kFileStart; memcpy(&chunkData[1], fileSize.c_str(), sizeLength); chunkData[sizeLength + 1] = '\0'; events->addEvent(CEvent(events->forIScreen().fileChunkSending(), eventTarget, sizeMessage)); // send chunk messages with a fixed chunk size size_t sentLength = 0; size_t chunkSize = m_chunkSize; CStopwatch stopwatch; stopwatch.start(); file.seekg (0, std::ios::beg); while (true) { if (stopwatch.getTime() > PAUSE_TIME_HACK) { // make sure we don't read too much from the mock data. if (sentLength + chunkSize > size) { chunkSize = size - sentLength; } // for fileChunk->m_chunk, the first byte is the chunk mark, last is \0 CFileChunk* fileChunk = new CFileChunk(chunkSize + 2); char* chunkData = fileChunk->m_chunk; chunkData[0] = kFileChunk; file.read(&chunkData[1], chunkSize); chunkData[chunkSize + 1] = '\0'; events->addEvent(CEvent(events->forIScreen().fileChunkSending(), eventTarget, fileChunk)); sentLength += chunkSize; file.seekg (sentLength, std::ios::beg); if (sentLength == size) { break; } stopwatch.reset(); } } // send last message CFileChunk* transferFinished = new CFileChunk(2); chunkData = transferFinished->m_chunk; chunkData[0] = kFileEnd; chunkData[1] = '\0'; events->addEvent(CEvent(events->forIScreen().fileChunkSending(), eventTarget, transferFinished)); file.close(); }
int main(int argc, char *argv[]) { int max_threads = -1; int use_invasic = 1; if (argc > 1) use_invasic = atoi(argv[1]); if (use_invasic) std::cout << "INVASIC ACTIVATED" << std::endl; else std::cout << "INVASIC NOT ACTIVATED" << std::endl; int verbose_level = 0; if (argc > 2) verbose_level = atoi(argv[2]); /* * initialize MPI */ int rank, size; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); if (size == 1) { std::cout << "run with `mpirun -n 2 ./build/client_mpi_tbb_release [use invasic (0/1)] [verbose level (-99 for fancy graphics)]`" << std::endl; return -1; } CWorldScheduler_threaded *cWorldScheduler_threaded; if (use_invasic > 0) { /* * allocate & start iPMO server for 1st rank on numa-domain */ if (rank == 0) { if (use_invasic == 1) { cWorldScheduler_threaded = new CWorldScheduler_threaded; std::cout << "RANK 0: starting worldscheduler" << std::endl; cWorldScheduler_threaded->start(-1, verbose_level, true); } } /* * WAIT FOR WORLD SCHEDULER! */ MPI_Barrier(MPI_COMM_WORLD); /* * initialize iPMO client */ #if USE_OMP cPmo = new CPMO_OMP(max_threads); #else cPmo = new CPMO_TBB(max_threads); #endif // initial setup request cPmo->invade_blocking(1, 1024, 0, nullptr, (float)1); } CStopwatch cStopwatch; cStopwatch.start(); /* * start simulation */ for (int t = 0; t < 100; t++) { if (rank == 0) std::cout << "Timestep: " << t << std::endl; // compute some workload int workload = (t*((rank+size-1)%size) + (100-t)*rank) % 100; // for 4 cores only on my laptop, a linear imbalance is not working on dual-core systems workload *= workload; std::cout << " > rank " << rank << " workload: " << workload << std::endl; if (use_invasic > 0) { // is some message about optimizations available? cPmo->reinvade_nonblocking(); // request resource update with new workload cPmo->invade_nonblocking(1, 1024, 0, nullptr, (float)workload); } int n; if (use_invasic > 0) { n = cPmo->getNumberOfThreads(); } else { n = sysconf(_SC_NPROCESSORS_ONLN)/size; } /* * spread some bogus workload across n threads */ #if USE_OMP #pragma omp parallel for schedule(static, 1) for (int i = 0; i < n; i++) { CDummyWorkload::doSomeSqrt(991290391.0, workload/n); } #else tbb::parallel_for( 0, n, 1, [workload,n](int i) { CDummyWorkload::doSomeSqrt(991290391.0, workload/n); } ); #endif std::cout << " > rank " << rank << " finished" << std::endl; // do some stupid barrier MPI_Barrier(MPI_COMM_WORLD); } double t = cStopwatch.getTimeSinceStart(); std::cout << "runtime: " << t << std::endl; if (use_invasic > 0) { // NEVER MIX retreat() with nonblocking invade/reinvade! // cPmo_TBB->retreat(); /* * free iPMO client */ delete cPmo; // wait for all clients to shutdown iPMO MPI_Barrier(MPI_COMM_WORLD); /* * free iPMO server */ if (rank == 0) { if (use_invasic == 1) delete cWorldScheduler_threaded; } } MPI_Finalize(); return EXIT_SUCCESS; }
bool CXWindowsPrimaryScreen::showWindow() { assert(m_window != None); CDisplayLock display(m_screen); // raise and show the input window XMapRaised(display, m_window); // grab the mouse and keyboard. keep trying until we get them. // if we can't grab one after grabbing the other then ungrab // and wait before retrying. give up after s_timeout seconds. static const double s_timeout = 1.0; int result; CStopwatch timer; do { // keyboard first do { result = XGrabKeyboard(display, m_window, True, GrabModeAsync, GrabModeAsync, CurrentTime); assert(result != GrabNotViewable); if (result != GrabSuccess) { LOG((CLOG_DEBUG2 "waiting to grab keyboard")); ARCH->sleep(0.05); if (timer.getTime() >= s_timeout) { LOG((CLOG_DEBUG2 "grab keyboard timed out")); XUnmapWindow(display, m_window); return false; } } } while (result != GrabSuccess); LOG((CLOG_DEBUG2 "grabbed keyboard")); // now the mouse result = XGrabPointer(display, m_window, True, 0, GrabModeAsync, GrabModeAsync, m_window, None, CurrentTime); assert(result != GrabNotViewable); if (result != GrabSuccess) { // back off to avoid grab deadlock XUngrabKeyboard(display, CurrentTime); LOG((CLOG_DEBUG2 "ungrabbed keyboard, waiting to grab pointer")); ARCH->sleep(0.05); if (timer.getTime() >= s_timeout) { LOG((CLOG_DEBUG2 "grab pointer timed out")); XUnmapWindow(display, m_window); return false; } } } while (result != GrabSuccess); LOG((CLOG_DEBUG1 "grabbed pointer and keyboard")); return true; }