我用std :: chrono C++庫編寫了下面的代碼,我試圖做的是 修復應用程序的FPS
60,但我得到50 FPS
,肯定不是性能問題 ,因爲我沒有計算任何東西。但它肯定是一個無效的使用或錯誤。使用std :: chrono庫來調整應用程序的fps,但得到奇怪的行爲
的TARGET_FPS
宏設置爲目標FPS
,我想,然後 顯示真正的實際的FPS,以下這些行控制檯窗口中顯示我設置TARGET_FPS
的價值觀,每個被關聯到最終FPS
。
TARGET_FPS---->FPS
60----->50
90----->50
100----->100
1000----->100
10000----->100
whatever ----->100
即使我定義TARGET_FPS
1000000000我得到100 FPS
,甚至當我將它定義到458或任何值超過100,我會得到100 FPS
作爲輸出。
#include <chrono> /// to use std::chrono namespace
#include <iostream> /// for console output
#include <thread> /// for std::this_thread::sleep_for()
#define TARGET_FPS 60// our target FPS
using frame_len_type = std::chrono::duration<float,std::ratio<1,TARGET_FPS>>; /// this is the duration that defines the length of a frame
using fsecond = std::chrono::duration<float>; /// this duration represents once second and uses 'float' type as internal representation
const frame_len_type target_frame_len(1); /// we will define this constant here , to represent on frame duration (defined to avoid construction inside a loop)
void app_logic(){ /** ... All application logic goes here ... **/}
int main() /// our main function !
{
using sys_clock = std::chrono::system_clock; /// simplify the type name to make the code readable
sys_clock::time_point frame_begin,frame_end; /// we will use these time points to point to frame begin and end
while (true)
{
frame_begin = sys_clock::now(); /// there we go !
app_logic(); /// lets be logical here :)
frame_end = sys_clock::now(); /// we are done so quick !
std::this_thread::sleep_for(target_frame_len- (frame_end.time_since_epoch()-frame_begin.time_since_epoch())); /// we will take a rest that is equal to what we where supposed to take to finish the actual target frame length
std::cout<< fsecond(1)/(sys_clock::now() - frame_begin) <<std::endl; /// this will show ass the current FPS
}
return 0; /// return to OS
} /// end of code
[Can not](https://wandbox.org/permlink/w60n36CqXJamqgpi)[reproduce](https://wandbox.org/permlink/CpyJSQOOVchxQJwx)[it](https://wandbox.org/permlink/u1i9mfXY0BEgVzOh )實際上。你介意給更多的上下文嗎?編譯器,主機系統等。 – skypjack
如果您使用的是Windows,那麼您無法使用睡眠來實現此類行爲。參見[https://stackoverflow.com/questions/85122/how-to-make-thread-sleep-less-than-a-millisecond-on-windows](https://stackoverflow.com/questions/85122/how -to-使線程睡眠低於一毫秒式窗口)。即使你正在使用別的東西,你最好花時間等待傳入的事件,而不只是睡覺。 – VTT
@skypjack 操作系統:Microsoft Windows 7專業美髮 版本:6.1.7601 Service Pack 1個版本7601 類型:基於x64的PC Processeur(S):安裝1個processeur: [01]:Intel64位家庭6型號69步進1 GenuineIntel〜799 MHz BIOS版本:Insyde Corp. V1.26,2014年12月18日 –