SFML community forums

Help => Window => Topic started by: Nuckal777 on July 27, 2019, 12:24:05 am

Title: isKeyPressed sometimes slow on linux
Post by: Nuckal777 on July 27, 2019, 12:24:05 am
Hello  :) ,

while i was working on the performance of game i realized that sf::Keyboard::isKeyPressed returns slowly at random timings. The following minimal working example showed that on my system (ArchLinux, gcc 9.1, with sfml 2.5.1) one call to sf::Keyboard::isKeyPressed takes around 10 ticks normally. At random intervals it jumps to 110-150 ticks (at 1 million ticks per second)  :o , while I don't press any key and keeping the window just open.
Code: [Select]
#include "SFML/Graphics.hpp"
#include <iostream>
int main() {
    sf::RenderWindow window(sf::VideoMode(800, 600), "My window");
    while (window.isOpen())
    {
        sf::Event event;
        while (window.pollEvent(event))
        {
            if (event.type == sf::Event::Closed)
                window.close();
        }
        clock_t start = clock();
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)){
            std::cout << "A" << std::endl;
        }
        clock_t end = clock() - start;
        if (end > 100) std::cout << end << std::endl;
        window.clear(sf::Color::Blue);
        window.display();
    }
    return 0;
}
In the game I currently check for 9 keys, where the times seems to add up leading to low minimal fps as I check during rendering. Am I missing something obvious here? Should I split the rendering and input into different threads? Moreover each call to isKeyPressed fetches the whole keymap of X11. Is it advisable to get it once and check all required keys against it?
Title: Re: isKeyPressed sometimes slow on linux
Post by: eXpl0it3r on July 27, 2019, 08:35:29 am
Is it really a noticable issue or are you just prematurely optimizing things?

isKeyPressed does make some system calls, so it might be that the system is busy with other stuff first. The best alternative is to use events and do your own key state tracking.
Title: Re: isKeyPressed sometimes slow on linux
Post by: Nuckal777 on July 27, 2019, 11:21:47 am
Is it really a noticable issue or are you just prematurely optimizing things?

It brought my application below 144 fps regularly. But keeping track of the keyboard state using events fixed it. Thank you  :D.