0

Bit of a noob here. I'm making a basic Pong clone game in C++ with SFML, but when I run the .exe on other computers the program runs (for most other PCs) slower. I've used Java before and used this way to regulate the amount of updates per second:

    long lastTime = System.nanoTime();
    final double ns = 1000000000.0 / 60.0;
    double delta = 0;

    while(running)
        {
            long now = System.nanoTime();
            delta += (now - lastTime) / ns;
            lastTime = now;
            while(delta >= 1)
                {
                    update();
                    delta--;
                }
        render();
        }                               
    }

I was planning on using this, but does C++ have anything like Java's System.nanoTime() method? How else could I make sure that my programs run at (or at least appear to run at) the same speed on different computers?

-Windows 7, VS2010.

user3213175
  • 37
  • 3
  • 9

2 Answers2

1

For Windows, you could try timeGetTime or QueryPerformanceCounter. The former is much easier to digest, although slightly less accurate.

For non-Windows folk, you could use clock or time. There are tons of others out there, too.

Community
  • 1
  • 1
Proxy
  • 1,824
  • 1
  • 16
  • 27
1

You can either use the C++11 <chrono> header with all it's time functions or since you're already using SFML, you can use its functions directly. There's window.setFramerateLimit(uint), which uses sleep() to reduce the CPU usage if possible, however sleep() always has some inaccuracy. Then there's window.setVerticalSyncEnabeled(bool), which will (de-)activate VSync. It's the way you most likely want to go, keep in mind however that VSync can be forced off by the driver.

For keeping track of the time you can use sf::Time and sf::Clock. sf::Time is just a container that holds a certain timespan and can be easily converted to seconds, milliseconds and microseconds. sf::Clock can only be restarted, they are not stop watches (see here if you need such a functionality), but you can retrieved that time passed as sf::Time object, since the clock was reset last.

Don't forget to go through the SFML tutorials and the documentation, they contain about anything you'd want to know about SFML.

Btw. working with nanoseconds is more of an illusion than anything, it's not very accurate and if your game would need such a small resolution, your game logic might need some optimizing.

Lukas
  • 2,461
  • 2
  • 19
  • 32