考虑这个例子,我用 gpuQueue.wait() 等待完成:
constexpr unsigned dataSize = 1024;
std::vector<float> in1 (dataSize, 0); std::iota(in1.begin(), in1.end(), 0 );
std::vector<float> in2 (dataSize, 0); std::iota(in2.begin(), in2.end(), 25);
std::vector<float> out (dataSize, 0);
float coeff1 = 4;
cl::sycl::buffer<float, 1> bufIn1(in1.data(), dataSize);
cl::sycl::buffer<float, 1> bufIn2(in2.data(), dataSize);
cl::sycl::buffer<float, 1> bufOut(out.data(), dataSize);
cl::sycl::queue gpuQueue{cl::sycl::gpu_selector()};
gpuQueue.submit([&](cl::sycl::handler &cgh) {
auto in1 = bufIn1.get_access<cl::sycl::access::mode::read> (cgh);
auto in2 = bufIn2.get_access<cl::sycl::access::mode::read> (cgh);
auto temp = bufOut.get_access<cl::sycl::access::mode::write>(cgh);
auto kernel = [=](cl::sycl::id<1> id) {
temp[id] = in1[id] * in2[id] + coeff1;
};
cgh.parallel_for<floatIteration>(cl::sycl::range<1>(dataSize), kernel);
});
gpuQueue.wait();
for( unsigned i = 0; i < dataSize; ++i )
std::cout << out[i] << " " << (in1[i] * in2[i] + coeff1) << "\n";
而这个缓冲区位于嵌套范围内且无需等待的示例:
constexpr unsigned dataSize = 1024;
std::vector<float> in1 (dataSize, 0); std::iota(in1.begin(), in1.end(), 0 );
std::vector<float> in2 (dataSize, 0); std::iota(in2.begin(), in2.end(), 25);
std::vector<float> out (dataSize, 0);
float coeff1 = 4;
{
cl::sycl::buffer<float, 1> bufIn1(in1.data(), dataSize);
cl::sycl::buffer<float, 1> bufIn2(in2.data(), dataSize);
cl::sycl::buffer<float, 1> bufOut(out.data(), dataSize);
cl::sycl::queue gpuQueue{cl::sycl::gpu_selector()};
gpuQueue.submit([&](cl::sycl::handler &cgh) {
auto in1 = bufIn1.get_access<cl::sycl::access::mode::read>(cgh);
auto in2 = bufIn2.get_access<cl::sycl::access::mode::read>(cgh);
auto temp = bufOut.get_access<cl::sycl::access::mode::write>(cgh);
auto kernel = [=](cl::sycl::id<1> id) {
temp[id] = in1[id] * in2[id] + coeff1;
};
cgh.parallel_for<floatIteration>(cl::sycl::range<1>(dataSize), kernel);
});
}
for( unsigned i = 0; i < dataSize; ++i )
std::cout << out[i] << " " << (in1[i] * in2[i] + coeff1) << "\n";
两者的输出是:
queue.wait() | 嵌套范围 |
---|---|
0 4 | 4 4 |
0 30 | 30 30 |
0 58 | 58 58 |
为什么 queue.wait() 不等待将缓冲区中的数据复制回主机?