【问题标题】:How to measure thread time for progress bar?如何测量进度条的线程时间?
【发布时间】:2019-02-27 19:38:23
【问题描述】:

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

进度条

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;

当然进度条会在执行后更新,所以不会实时显示。

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

【问题讨论】:

  • 可能取决于您使用的进度条类型。它是否有接口以估计时间属性的形式最大限度地传达?应该使用什么时间分辨率(实时不是真的,每一种实时都是基于一定的分辨率,操作系统能保证)?
  • 它被编程为从 0.0f 到 1.0f。我认为时间可能以毫秒为单位,我会将其转换为 0.0f -> 1.0f
  • 恐怕您必须更具体地了解您的 GUI 框架,您正在使用什么具体的 ProgressBar,您如何配置它,以及您打算如何更新它。我认为这应该是显示尝试的问题中包含的最少代码。
  • 更改 do sth 以定期报告进度..
  • 好吧,我以为进度条是进度条,但如果是的话。我已经更新了问题。

标签: c++ multithreading progress-bar


【解决方案1】:

您可以为进度条做的所有事情就是根据您已经完成的工作(估计(或确切了解)要完成的总工作量)显示估计或您已经完成了多长时间。

您所知道的只是完成了哪些工作以及花费了多少时间。做所有事情所花费的时间总是一个估计。根据已经完成的工作进行估算,通常可以做得很好,但并非总是如此。

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

【讨论】:

  • 所以,我应该定期报告进度,就像 rustyx 建议的那样。但是,如何做到这一点。
  • @JarekBisnesu 如果您自己编写所有内容,则需要添加回调功能,以便线程可以将消息发送到进度条以使进度条保持最新。如果您使用的是框架,那么这个管道内置的可能性很大(例如.Net BackgroundWorker)。
  • 我更喜欢自己编写所有内容,因为我想学习一些东西并知道它是如何工作的,而不仅仅是使用它。我会尝试考虑(和谷歌)如何添加回调功能,稍后我会告诉你。
  • 您使用的是什么 GUI 库或框架?任何答案都取决于此。
  • 也许你想要 boost::signals2 为此:theboostcpplibraries.com/boost.signals2-multithreading
猜你喜欢
  • 2012-02-02
  • 2019-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-16
  • 2017-12-08
  • 2021-05-05
  • 2015-02-20
相关资源
最近更新 更多