c++ - 使用推力(素数)在 GPU 中编译

标签 c++ thrust

我有一个用 C 语言用 thrust 编写的代码,但我无法编译它,因为我没有 GPU。我的代码应该计算前 1000 个素数。就是这样。但问题是

1 - 我无法编译它,因为我没有 GPU。

2 - 因为我无法编译它,所以我不知道它是否真的计算素数。

这是我的代码:

`struct prime{
_host_ _device_
    void operator()(long& x){
    bool result = true;
    long stop = ceil(sqrt((float)x));
    if(x%2!=0){
        for(int i = 3;i<stop;i+=2){
            if(x%i==0){
                result = false;
                break;
            };
        }
    }else{
        result = false;
    }
    if(!result)
        x = -1;
 }
};
void doTest(long gen){
  using namespace thrust;
  device_vector<long> tNum(gen);
  thrust::sequence(tNum.begin(),tNum.end());
}
int main(){
   doTest(1000);
   return 0;
}`

谁能帮我编译我的代码并显示结果,如果不能正常工作,然后帮我修复它?

最佳答案

如果您没有 GPU,请使用 thrust::host_vector 而不是 thrust::device_vector

我已经清理了你的代码,它在 CPU 上运行是这样的:

#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include <thrust/sequence.h>

#include <iostream>


int main()
{
    thrust::host_vector<long> tNum(1000);
    thrust::sequence(std::begin(tNum), std::end(tNum));
    thrust::transform(std::cbegin(tNum), std::cend(tNum), std::begin(tNum), [](long x)
    {
        bool result = true;
        long stop = (long)std::ceil(std::sqrt((float)x));
        if (x % 2 != 0) {
            for (long i = 3; i < stop; i += 2) {
                if (x % i == 0) {
                    result = false;
                    break;
                };
            }
        } else {
            result = false;
        }
        if (!result) x = -1;
        return x;
    });
    for (const auto& element : tNum) if (element>0) std::cout << element << ", ";
    std::cout << std::endl;

    std::cin.ignore();
    return 0;
}

关于c++ - 使用推力(素数)在 GPU 中编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50689658/

相关文章:

c++ - 使用推力减少计数

c++ - 将 CUDA 分配 char * 到对象的 device_vector

c++ - 集群地形图通过 map /矩阵与河流不相交?

c++ - 有什么方法可以从 C++ 中的成员指针类型派生对象类型

c# - 在 XAML 应用程序中引用 C++ 组件

c++ - CUDA/推力图像处理

c++ - 更改派生类型的对齐方式

cuda - 同时使用 2 个 GPU 调用 cudaMalloc 时性能较差

c++ - 不允许使用抽象类数组

c++ - std::unique_ptr<T[]>::reset 在 gcc 6 中的实现