I've noticed this ever since I started playing games, and now see it in my own experiments. If I don't do any capping my game runs at 200~250 FPS, with random drops to 150FPS, but if I cap the FPS to 60 using a simple precision timer + sleep method, the game will sometimes (much more frequently than I want) render at ~40FPS during complex scenes.
I suspect this is simply because my process gets dequeued by the OS during the time I used to spend rendering the other 140 frames, meaning there's more context switches going on, as well as allowing other processes to steal all the cores and do CPU-intensive tasks in them. At the same time, this doesn't feel right, and one would think modern OS's are able to do scheduling that is good enough to avoid that.
So, my question is, are there any techniques to optimize my game for constant FPS rather than high-but-with-lots-of-variation FPS? Should I just make sure my game logic is being updated in a constant rate and don't worry about render rates?
Here's how my FPS-limiting code looks like (somehow pseudo code):
const maxFrameTime = 1/DESIRED_FPS; // say 60
while(running()) {
now = query_precision_timer();
thisFrame = now - lastFrame;
lastFrame = now;
while(thisFrame > 0.) {
Update();
thisFrame -= maxFrameTime;
now += maxFrameTime;
}
Render();
}