2

I'm writing an OpenGL application. At the beginning it has very large CPU consumption in SwapBuffer (profiled in Intel VTune Profiler) that made my user unhappy. I made some search and somebody says you should sleep for some time until vsync, so I make the OpenGL thread sleep like this:

// in OpenGL thread
auto render_start = std::chrono::steady_clock::now();
do_render();
auto render_end = std::chrono::steady_clock::now();
auto render_length = render_end - render_start;
auto expect_length = std::chrono::milliseconds( 1000 / 60 - 1 ); // an extra 1 ms gap to prevent oversleep
if (expect_length > render_length)
    std::this_thread::sleep_for( expect_length - render_length );

However, in task manager, the CPU cost does not decrease. Detailed analysis in Intel VTune Profiler shows that sleep costs a large amount of CPU spin time, whilst total amount of CPU consumption is approximately same with the version without sleep. So is there any way to truely reduce CPU cost of SwapBuffer or sleep?

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
jiandingzhe
  • 1,881
  • 15
  • 35
  • 2
    `1000 / 60 - 1`: 15. If you are on Windows and didn't change the scheduler time slots, they might have a default value of round about 16 ms. Thus, the `sleep_for()` with 15 ms might come out as a zero-like sleep. However, this is all a bit speculative... – Scheff's Cat Jan 10 '22 at 06:37
  • 2
    FYI: [SO: Unpredictable behaviour of std::sleep_for on Windows 10](https://stackoverflow.com/q/54493041/7478597) If you are on Windows, it even may change if you start e.g. a media player. The scheduler time slots are a global resource. If any process makes the time slots shorter it affects all processes. – Scheff's Cat Jan 10 '22 at 06:42
  • 1
    FYI: [SO: Precise thread sleep needed. Max 1ms error](https://stackoverflow.com/q/13397571/7478597) – Scheff's Cat Jan 10 '22 at 06:46

0 Answers0