大约c:SDL_GetTicks()的精度低于毫秒级

SDL_GetTicks() accuracy below the millisecond level

我目前正在使用SDL2进行编程。
一切正常,但是SDL_GetTicks()方法有问题。
通常,它应该返回总的应用程序时间(以毫秒为单位),但在大多数情况下始终返回值0,有时返回值1。

我用SDL_INIT_EVERYTHING标志初始化了SDL。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#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();
}


如果想要更高的精度,则不能使用SDL_GetTicks(),但还有许多其他选择。如果要独立于平台,则需要谨慎,但是以下是一个可移植的C 11示例,它将帮助您入门:

1
2
3
4
5
6
7
8
9
10
11
12
#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上运行它给了我:

1
Delta t2-t1: 282 nanoseconds


当然,您需要等到> = 1ms才能更新最后的滴答计数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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;
    }  
}