I've been working on making a basic game loop in C++ and I'm unsure my logic is completely right as my delta time isn't what I expect. I expect to get 1/60 seconds per frame as my cap is 60fps, but over the average I take I get a delta time of ~0.03 seconds per frame giving me 33fps. I know the program can run faster than this as if I raise the frame cap it has a smaller delta time, which is still inaccurate. Any help? (I've removed unimportant bits of code to focus on the logic)
using namespace std::chrono;
int main(void)
{
//Init time - start and end, with delta time being the time between each run of the loop
system_clock::time_point startTime = system_clock::now();
system_clock::time_point endTime = system_clock::now();
float deltaTime = 0.0f;
//*Game made here*
/* Loop until the user closes the window */
while (window is not closed)
{
//Takes time at start of loop
startTime = system_clock::now();
deltaFrameCount++;
//Handle game processes
//Get time at end of game processes
endTime = system_clock::now();
//Take time during work period
duration<double, std::milli> workTime = endTime - startTime;
//Check if program took less time to work than the cap
if (workTime.count() < (milliseconds per frame cap))
{
//Works out time to sleep for by casting to double
duration<double, std::milli> sleepDurationMS((milliseconds per frame cap) - workTime.count());
//Casts back to chrono type to get sleep time
auto sleepDuration = duration_cast<milliseconds>(sleepDurationMS);
//Sleeps this thread for calculated duration
std::this_thread::sleep_for(milliseconds(sleepDuration.count()));
}
//get time at end of all processes - time for one whole cycle
endTime = system_clock::now();
duration<double, std::milli> totalTime = endTime - startTime;
deltaTime = (totalTime / 1000.0f).count();
}
//cleans game
return 0;
}