c++ 将数据从设备存储到主存

yftpprvb  于 2023-06-07  发布在  其他
关注(0)|答案(1)|浏览(141)

我有一个设备矢量,我不断修改,然后想保存在一个HDF5文件。由于设备向量的大小,我不能进行多次修改,然后保存它们以减少与移动数据有关的开销。下面是我的代码的一个例子。目前,在每个步骤中保存数据会使运行时间增加10倍以上。我能做些什么来加快我的代码?

#include <thrust/device_vector.h>
#include <thrust/transform.h>

struct modifier
{
    template <typename T>
    __host__ __device__
    void operator()(T data)
    {
        // Making some modification, for example:
        return data + 1;
    }
};

struct writer
{
    template <typename T>
    void operator()(T data)
    {
        // Opening my HDF5 file, the subset to write on and then write on
    }
};

int main()
{
    thrust::device_vector<int> data(1000000);
    writer write;

    int i = 0;

    while(i < 1000000)
    {
        thrust::tranform(data.begin(), data.end(), data.begin(), modifier());
        write(data); // This line slows down everything by a lot
        i++;
    }

    return 0;
}
kknvjkwl

kknvjkwl1#

您可以改为写入缓冲区。
IO通常是应用程序中最慢的部分之一。不写文件,你可以写std::vector或其他合适的容器,然后刷新这个缓冲区,例如当writer超出作用域时(在它的析构函数中)。
这带来的缺点是,如果您的应用程序崩溃,您的数据可能会丢失。
标准库在std::coutstd::cerr的实现中使用了这种方法,其中前者是缓冲输出,后者是无缓冲输出。

相关问题