【问题标题】:Execution order of c++c++的执行顺序
【发布时间】:2015-06-24 17:39:09
【问题描述】:

我创建了一个测试carchive 的程序。我想看看保存一百万个数据点需要多快:

#include "stdafx.h"
#include "TestData.h"
#include <iostream>
#include <vector>

using namespace std;

void pause() {
    cin.clear();
    cout << endl << "Press any key to continue...";
    cin.ignore();
}

int _tmain(int argc, _TCHAR* argv[])
{
    int numOfPoint = 1000000;

    printf("Starting test...\n\n");
    vector<TestData>* dataPoints = new vector<TestData>();

    printf("Creating %i points...\n", numOfPoint);
    for (int i = 0; i < numOfPoint; i++)
    {
        TestData* dataPoint = new TestData();
        dataPoints->push_back(*dataPoint);
    }
    printf("Finished creating points.\n\n");

    printf("Creating archive...\n");
    CFile* pFile = new CFile();
    CFileException e;
    TCHAR* fileName = _T("foo.dat");
    ASSERT(pFile != NULL);
    if (!pFile->Open(fileName, CFile::modeCreate | CFile::modeReadWrite | CFile::shareExclusive, &e))
    {
        return -1;
    }

    bool bReading = false;
    CArchive* pArchive = NULL;
    try
    {
        pFile->SeekToBegin();
        UINT uMode = (bReading ? CArchive::load : CArchive::store);
        pArchive = new CArchive(pFile, uMode);
        ASSERT(pArchive != NULL);
    }
    catch (CException* pException)
    {
        return -2;
    }
    printf("Finished creating archive.\n\n");

    //SERIALIZING DATA
    printf("Serializing data...\n");
    for (int i = 0; i < dataPoints->size(); i++)
    {
        dataPoints->at(i).serialize(pArchive);
    }
    printf("Finished serializing data.\n\n");

    printf("Cleaning up...\n");
    pArchive->Close();
    delete pArchive;
    pFile->Close();
    delete pFile;
    printf("Finished cleaning up.\n\n");

    printf("Test Complete.\n");

    pause();

    return 0;
}

当我运行此代码时,创建数据点需要一些时间,但它几乎会立即运行其余代码。但是,我必须等待大约 4 分钟才能让应用程序真正完成运行。我会假设应用程序会在序列化数据部分等待挂起,就像它在创建数据点期间所做的那样。

所以我的问题是关于这实际上是如何工作的。 carchive 是否在单独的线程上执行它的操作并允许其余代码执行?

如有需要,我可以提供更多信息。

【问题讨论】:

  • 不要那样向你的向量中添加元素!! dataPoints-&gt;push_back(*dataPoint);你正在泄露每一个元素stackoverflow.com/questions/9303921/…
  • 感谢您的提醒!
  • 你也没有理由newstd::vector
  • 请避免使用MFC(在控制台应用中无用,对初学者有害)
  • 在这个程序中可能根本没有理由使用new。删除那些对new 的调用使那些ASSERT 行变得不必要,因为您将处理对象,而不是指针。

标签: c++ carchive


【解决方案1】:

如果你想创建一个包含一百万个默认初始化的元素的向量,你只需使用这个版本的构造函数

vector<TestData> dataPoints{numOfPoint};

你应该停止 newing 一切,让 RAII 为你处理清理工作。

另外,如果容量不够大,push_back 需要向量的 resize,所以如果你从一个空向量开始,并且知道它最后会有多大,你可以提前使用reserve

vector<TestData> dataPoints;
dataPoints.reserve(numOfPoint);
for (int i = 0; i < numOfPoint; i++)
{
    dataPoints->push_back(TestData{});
}

【讨论】:

  • 这有帮助。原来它花了 4 分钟解除分配。
猜你喜欢
  • 1970-01-01
  • 2011-05-21
  • 1970-01-01
  • 2021-10-02
  • 2012-10-30
  • 1970-01-01
  • 2022-01-06
  • 2013-10-17
  • 1970-01-01
相关资源
最近更新 更多