SDL_GetTicks()精度低于毫秒级

时间:2014-10-18 14:33:39

标签: c++ sdl sdl-2 timedelta

我目前用SDL2编程。 一切正常,但我的SDL_GetTicks()方法有问题。 通常它应该以毫秒为单位返回总应用程序时间,但它总是返回值0的大部分时间,有时返回值1.

我用SDL_INIT_EVERYTHING标志初始化了SDL。

以下代码的问题是循环太快,因此增量时间小于1 ms。有没有一种方法可以达到更高的精度?

#include "Application.hpp"

void Application::Initialize()
{
    int sdl_initialize_result = SDL_Init(SDL_INIT_EVERYTHING);
    if(sdl_initialize_result < 0)
    {
        std::cerr << "Failed to initialize SDL !" << std::endl << SDL_GetError() << std::endl;
    }

    window = SDL_CreateWindow("Project Unknown", 100, 100, 800, 600, SDL_WINDOW_SHOWN);
    if(window == nullptr)
    {
        std::cerr << "Failed to create  SDL window !" << std::endl << SDL_GetError() << std::endl;
    }

    last_update_time = SDL_GetTicks();
}

void Application::Dispose()
{
    SDL_DestroyWindow(window);
    SDL_Quit();
}

void Application::Render()
{
}

void Application::Update()
{
    Uint32  current_time = SDL_GetTicks();
    Uint32  delta_time = current_time - last_update_time;


    SDL_Event event;
    while(SDL_PollEvent(&event))
    {
        switch(event.type)
        {
            case SDL_QUIT:
            {
                should_close = true;
            }
            break;

            default:
            {

            }
            break;
        }
    }

    // Update game objects with delta_time

    last_update_time = current_time;
}


void Application::Run()
{
    Initialize();

    should_close = false;
    do
    {
        Render();
        Update();
    }
    while(should_close == false);

    Dispose();
}

2 个答案:

答案 0 :(得分:6)

如果您想要更高的精度,则不能使用SDL_GetTicks(),但还有许多其他选择。如果你想要独立于平台,你需要小心,但这是一个可以让你入门的便携式C ++ 11示例:

#include <iostream>
#include <chrono>
typedef std::chrono::high_resolution_clock Clock;

int main()
{
    auto t1 = Clock::now();
    auto t2 = Clock::now();
    std::cout << "Delta t2-t1: " 
              << std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count()
              << " nanoseconds" << std::endl;
}

在ideone.com上运行这个给了我:

Delta t2-t1: 282 nanoseconds

答案 1 :(得分:2)

当然,你需要等到&gt; = 1ms已经过去才更新你的最后一次滴答计数

void Application::Update()
{
    Uint32  current_time = SDL_GetTicks();
    Uint32  delta_time = current_time - last_update_time;

    SDL_Event event;
    while(SDL_PollEvent(&event))
    {
        switch(event.type)
        {
            case SDL_QUIT:
            {
                should_close = true;
            }
            break;

            default:
                break;
        }
    }

    if (delta_time >= 1)
    {
        // Update game objects with delta_time

        last_update_time = current_time;
    }   
}