如何衡量进度条的线程时间?

问题描述 投票:0回答:1

我想跟随一个线程进展。我已经以图形方式实现了进度条,但我想知道如何有效地实时测量线程的进度。

进度条

template<typename T>
inline T Saturate(T value, T min = static_cast<T>(0.0f), T max = static_cast<T>(1.0f))
{
    return value < static_cast<T>(min) ? static_cast<T>(min) : value > static_cast<T>(max) ? static_cast<T>(max) : value;
}

void ProgressBar(float progress, const Vector2& size)
{
    Panel* window = getPanel();

    Vector2 position = //some position                                                                                                                              
    progress = Saturate(progress);

    window->renderer->FillRect({ position, size }, 0xff00a5ff);
    window->renderer->FillRect(Rect(position.x, position.y, Lerp(0.0f, size.w, progress), size.h), 0xff0000ff);

    //progress will be shown as a %
    std::string progressText;       
    //ToString(value, how many decimal places)                                                                                                                        
    progressText = ToString(progress * 100.0f, 2) + "%";                                                

    const float textWidth = font->getWidth(progressText) * context.fontScale,
                textX = Clamp(Lerp(position.x, position.x + size.w, progress), position.x, position.x + size.w - textWidth);
    window->renderer->DrawString(progressText, Vector2(textX, position.y + font->getAscender(progressText) * context.fontScale * 0.5f), 0xffffffff, context.fontScale, *font.get());
}

以及游戏循环中的某个地方,示例用法

static float prog = 0.0f;
float progSpeed = 0.01f;
static float progDir = 1.0f;
prog += progSpeed * (1.0f / 60.0f) * progDir;

ProgressBar(prog, { 100.0f, 30.0f });

我知道如何衡量执行时间:

uint t1 = getTime();
//... do sth
uint t2 = getTime();
uint executionTime = t2 - t1;

但当然进度条会在执行后更新,因此不会实时显示。

我应该使用新线程吗?有没有其他方法可以做到这一点?

c++ multithreading progress-bar
1个回答
0
投票

您可以为进度条执行的操作是根据您已完成的工作(使用估计(或可能是确切的知识)显示要完成的工作来估计或进展多长时间。

你所知道的是所做的工作和所花的时间。做一切所需的时间总是一个估计。你可以通过基于已经完成的工作的估计来做得很好,但并非总是如此。

制定一个确切的进度条(在大多数情况下)是不可能的。你能做的最好的就是猜测。

© www.soinside.com 2019 - 2024. All rights reserved.