【问题标题】:Different time of the execution CListCtrl::InsertItem on the same amount of records在相同数量的记录上执行 CListCtrl::InsertItem 的不同时间
【发布时间】:2015-01-16 12:51:38
【问题描述】:

我有一个包含 10000 条记录的 CListCtrl,在程序启动时已填满,此操作的时间约为 1.3 秒。 但如果用户刷新列表,它会在 ~2.5 - 3 秒内填满。

在这两种情况下都使用相同的代码:

SetRedraw(FALSE);
SetItemCount(nCount);

// insert

SetRedraw(TRUE);

变量nCount在程序启动时等于0,在用户刷新列表时等于10000。

为什么列表填充的时间如此不同?

UPD:最少的代码

void CTestList::Init()
{
    InsertColumn(0, _T("Number"),   0, 50);
    InsertColumn(1, _T("Obj name"), 0, 150);
    InsertColumn(2, _T("Creator"),  0, 100);
    InsertColumn(3, _T("Editor"),   0, 100);
}

void CTestList::Reset()
{
    LVITEM item;

    item.iItem = 0;
    for (int i = 0; i < 10000; i++)
    {
        InsertRow(item, i);
        item.iItem++;
    }
}

void CTestList::InsertRow(LVITEM& item, int num)
{
    CString strNum;

    //
    item.iSubItem = 0;
    item.mask = LVIF_TEXT | LVIF_IMAGE | LVIF_PARAM;
    item.lParam = NULL;
    item.iImage = 0;

    strNum.Format(_T("%d"), num);
    item.pszText = (LPTSTR)(LPCTSTR)strNum;
    InsertItem(&item);

    //
    item.mask = LVIF_TEXT;
    item.iSubItem = 1;
    item.pszText = _T("Test object");
    SetItem(&item);

    //
    item.mask = LVIF_TEXT;
    item.iSubItem = 2;
    item.pszText = _T("Any one");
    SetItem(&item);

    // 
    item.iSubItem = 3;
    item.pszText = _T("Another one");
    SetItem(&item);
}

void CApp::FillList()
{
    CWaitCursor wait;

    m_list.DeleteAllItems();

    clock_t begin = clock();
    m_list.SetRedraw(FALSE);    
    m_list.SetItemCount(nCount);
    m_list.Reset();
    m_list.SetRedraw(TRUE);
    clock_t end = clock();

    double dif = static_cast<double>(end - begin) / CLOCKS_PER_SEC;

    CString str;

    str.Format(_T("Insertion time: %f"), dif);
    AfxMessageBox(str);
}

【问题讨论】:

  • 如果您能提供一个最小的、可重现的代码示例,将会非常有帮助。
  • 根据列表包含的项目类型,它可能需要先销毁所有项目,然后再推送新项目。
  • @csl 等一下,我会成功的
  • @RedX 是的,没错。我在SetRedraw(FALSE)之前做了DeleteAllItems(),但是这里没有写
  • 你为什么不使用virtual list

标签: c++ mfc clistctrl


【解决方案1】:

我已经在我的机器上测试了你的代码。仅当我在调试器中运行程序(使用 F5)时,我才能重现不同的时序,但如果我在没有调试器的情况下运行它(使用 Ctrl+F5 )。所以这似乎与您的代码或 Windows API 没有直接关系,而是与调试器有关。

【讨论】:

  • 我已经在调试器和发布版中运行了这段代码,并且还注意到,发布模式比调试器快得多。但这不是解决方案。在这两种情况下,第一个列表填充和后续列表填充之间的执行时间差异很大。
  • @brightside90:我不是在谈论调试/发布,只是在调试器下和没有调试器。在我的机器上,在没有调试器的情况下不运行程序时没有不同的时间。也许还有一些其他约束或其他相关代码您没有在您的问题中发布!?
  • 你是对的。那是我的遗漏 :( 我试图仅在调试/发布模式下运行程序,并且像“不使用任何模式运行程序怎么样?”这样的想法从未出现在我的脑海中 :( 谢谢,@ Werner Henze 现在每次运行程序并刷新列表时,我得到的时间大致相同。
猜你喜欢
  • 1970-01-01
  • 2020-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多