Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

libgdx - glClear takes too much time

Method Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); is taking too much time, around 15ms

Here is the code sample:

long now = System.currentTimeMillis();

Gdx.gl.glClearColor(0.1f, 0.1f, 0.1f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);


long end = System.currentTimeMillis() - now;//this is almost always > 15 ms
System.out.println("render time total: " + end);

This is on my android device (nexus 5), on my pc its 2-3 ms

like image 892
pedja Avatar asked Dec 19 '25 04:12

pedja


1 Answers

This is as expected. You're measuring the frame rate, not the execution time of glClear().

To understand what is happening here, you need to be aware that the GPU operates asynchronously to your CPU code. For example, when you call glClear(), you're submitting a command that tells the GPU to clear the framebuffer. The easiest way to picture how this works is that the command is added to a queue, which is processed by the GPU at a later point.

One consequence is that the framebuffer has generally not been cleared when the glClear() call returns. So measuring the time spent in the call is mostly unrelated to how long it takes to actually clear the framebuffer.

So what are you measuring? It's basically the frame rate. Android does not let you produce frames faster than the screen refresh rate, which is typically 60 Hz or slightly higher. At 60 Hz, the display shows a new frame every 16.667 ms, which is almost exactly the time you are measuring.

Your rendering needs to be throttled to match the display refresh rate, otherwise you would be producing frames at a much higher rate, and would queue up more and more work. The throttling could potentially happen anywhere, but it is fairly common to block the app at the start of a new frame when enough work is already queued up.

I believe most Android systems use triple buffering. This means that if two undisplayed frames are already queued up waiting to be displayed, and you start rendering another frame, your get blocked until one of the two pending frames is displayed at the next screen refresh.

This is actually very desirable behavior. Depending on the system and settings, some PC type devices let you render faster than the screen refresh rate. The result is that you render frames that never show up on the display, and are simply dropped. If you think about it, this is a complete waste. Particularly on battery powered and/or heat constrained devices, you don't want to do any unnecessary work. Throttling the rendering to match the screen refresh rate makes complete sense.

like image 147
Reto Koradi Avatar answered Dec 20 '25 18:12

Reto Koradi