c++ - 如何测量进度条的线程时间?
问题描述
我想关注线程进度。我已经以图形方式实现了进度条,但我想知道如何有效地实时测量线程的进度。
进度条
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;
但当然进度条会在执行后更新,所以不会实时显示。
我应该使用新线程吗?有没有其他方法可以做到这一点?
解决方案
您可以对进度条做的所有事情就是根据您已经完成的工作(估计(或者可能是确切的知识)要完成的总工作)显示估计或您已经完成了多长时间。
您所知道的只是完成了哪些工作以及花费了多少时间。做所有事情所花费的时间总是一个估计。根据已经完成的工作进行估算,通常可以做得很好,但并非总是如此。
制作一个准确的进度条(在大多数情况下)是不可能的。你能做的最好的就是猜测。