我写了一个基本程序,通过进入while循环并将循环内的时间与启动前的时间进行比较,将FPS降低到60 FPS左右,然后将FPS输出到控制台。
在同一个程序中,我有另一个代码块,可以使用类似的方法将FPS降低到10 FPS左右。
我想做的是使用OpenMP并行执行两个代码块,这样10 FPS块就不会减慢或干扰60FPS块。我的最终目标是让60 FPS的块以60 FPS的速度运行,即使程序中有一个循环,否则会将其降低到10 FPS。
我尝试过使用几种不同的OpenMP指令组合来实现这一点,但无论我使用什么指令,程序似乎总是以10 FPS的速度运行。
有可能将其与OpenMP一起使用吗?
这是代码:(编辑:我已经删除了dreamcrash提到的比赛条件,并修复了我注意到的其他一些错误(
#include <iostream>
#include <windows.h>
#include <stdint.h>
#include <omp.h>
int main() {
// Get the QueryPerformance frequency to measure the FPS
LARGE_INTEGER PerfCountFrequencyResult;
QueryPerformanceFrequency(&PerfCountFrequencyResult);
int64_t PerfCountFrequency = PerfCountFrequencyResult.QuadPart;
// 10 FPS for first thread
double Thread1TargetSecondsPerFrame = 1.0f / (double)10;
// 60 FPS for second thread
double Thread2TargetSecondsPerFrame = 1.0f / (double)60;
// Get Current time
LARGE_INTEGER LastCounter;
QueryPerformanceCounter(&LastCounter);
while(1){
#pragma omp parallel sections
{
// THREAD 1 (very slow 10FPS)
#pragma omp section
{
// Remove race condition
double SecondsElapsedForFrame;
// Get the seconds elapsed since last loop
LARGE_INTEGER CurrentCounter;
QueryPerformanceCounter(&CurrentCounter);
SecondsElapsedForFrame = ((float)(CurrentCounter.QuadPart - LastCounter.QuadPart) / (float)PerfCountFrequency);
// DELAY The time until it's 10FPS
if(SecondsElapsedForFrame < Thread1TargetSecondsPerFrame) {
while(SecondsElapsedForFrame < Thread1TargetSecondsPerFrame) {
// Get the seconds elapsed since last loop
QueryPerformanceCounter(&CurrentCounter);
SecondsElapsedForFrame = ((float)(CurrentCounter.QuadPart - LastCounter.QuadPart) / (float)PerfCountFrequency);
}
}
}
// THEAD 2 (should not be interrupted by THREAD 1)
#pragma omp section
{
// Remove race condition
double SecondsElapsedForFrame;
// Get the seconds elapsed since last loop
LARGE_INTEGER CurrentCounter;
QueryPerformanceCounter(&CurrentCounter);
SecondsElapsedForFrame = ((float)(CurrentCounter.QuadPart - LastCounter.QuadPart) / (float)PerfCountFrequency);
// DELAY the time until it's 60FPS
if(SecondsElapsedForFrame < Thread2TargetSecondsPerFrame) {
while(SecondsElapsedForFrame < Thread2TargetSecondsPerFrame) {
// Get the seconds elapsed since last loop
QueryPerformanceCounter(&CurrentCounter);
SecondsElapsedForFrame = ((float)(CurrentCounter.QuadPart - LastCounter.QuadPart) / (float)PerfCountFrequency);
}
}
// Get the seconds elapsed and output the FPS
QueryPerformanceCounter(&CurrentCounter);
double SecondsPerFrame = ((float)(CurrentCounter.QuadPart - LastCounter.QuadPart) / (float)PerfCountFrequency);
float FramesPerSecond = 1.0f/ SecondsPerFrame;
std::cout << "FPS:" << FramesPerSecond << "n";
// Get new time for beginning of loop
QueryPerformanceCounter(&LastCounter);
}
}
}
return(0);
}
首先是正确性的代码,然后是performance。
您的OpenMP程序是格式错误的,因为它包含SecondsElapsedForFrame
上的竞赛条件。事实上,变量在两个线程之间的并行区域中是隐式共享的,并且都写入其中。这也适用于LastCounter
。根据您的需要,您可能希望将它们制成private
、firstprivate
或lastprivate
。