cuda - CUDA Thrust 库中 counting_iterators 的用途和用法

标签 cuda iterator thrust

我无法理解 CUDA 推力库中的 counting_iterator。它的目的是什么,如何使用?它是否也适用于其他编程语言,例如 C++?

最佳答案

计数迭代器只是一个迭代器,它返回序列中的下一个值,每次迭代器递增时都会前进。最简单的例子是这样的:

#include <iostream>
#include <thrust/iterator/counting_iterator.h>

int main(void)
{
    int n = 10;

    thrust::counting_iterator<int>x(1);

    for(int i=0; i<n; ++i, ++x) {
        std::cout << *x << std::endl;
    }

    return 0;
}

在编译和运行时执行此操作:

$ /usr/local/cuda/bin/nvcc counting.cc 
$ ./a.out
1
2
3
4
5
6
7
8
9
10

即。计数迭代器初始化为值 1,每次迭代器递增时,我们都会得到计数序列中的下一个值,即。 1,2,3,4,5....

每当您需要一个序列来填充向量或在变换迭代器或仿函数中进行操作时,计数增量就会派上用场。计数迭代器消除了显式创建向量并用所需序列填充向量的需要。例如(来 self 对 this Stack Overflow question 的回答):

#include <thrust/device_vector.h>
#include <thrust/transform.h>
#include <thrust/functional.h>
#include <thrust/iterator/counting_iterator.h>
#include <thrust/iterator/constant_iterator.h>
#include <cstdio>

int main(void)
{
    const int N = 18, M = 3;
    thrust::device_vector<int> myvector(N);

    thrust::transform(  thrust::make_counting_iterator(0),
                        thrust::make_counting_iterator(N),
                        thrust::make_constant_iterator(M),
                        myvector.begin(),
                        thrust::divides<int>() );

    for(int i=0; i<N; i++) {
        int val = myvector[i];
        printf("%d %d\n", i, val);
    }
    return 0;
}

它生成一个设备向量,其中填充序列 0, 0, 0, 1, 1, 1, 2, 2 ,2, 3, 3, 3。

关于cuda - CUDA Thrust 库中 counting_iterators 的用途和用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18705190/

相关文章:

c++ - CUDA 中的复数/cuComplex 算术

rust - 在flat_map中返回不同种类的迭代器

javascript - 不会在 jQuery 中遍历数组

c++ - 字符串与指针比较的问题

cuda - 推力性能::计数

c++ - 确定推力的最大长度::device_vector

c++ - 无法使用 CUDA + MATLAB + Visual Studio 检查全局内存

visual-studio-2010 - 缺少 cutil 调试库 : Cannot open file cutil32D. lib

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

cuda - 动态并行性 - 启动许多小内核非常慢