CUDA Thrust库中计数迭代器的目的和用法

3

我有困难理解CUDA的thrust库中的counting_iterator。它的用途是什么,如何使用?其他编程语言(如C++)是否也可用?


Boost有一个计数迭代器(counting iterator),例如。 - talonmies
2个回答

4

计数迭代器就是一个迭代器,每次迭代器递增时,都从序列中返回下一个值。最简单的例子如下:

#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...

在Thrust中,计数增量在任何需要填充向量或在转换迭代器或函数对象中进行操作的情况下非常有用。计数迭代器消除了明确创建和填充所需序列的向量的需求。例如(来自我在此Stack Overflow问题中的回答):

#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。


2
作为进一步的例子,这是对@talonmies答案的轻微修改,您可以通过以下代码模拟Matlab的linspace命令。
#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>

void main()
{ 
    const int N = 20;

    float a     = 3.87f;
    float b     = 7.11f;

    float Dx    = (b-a)/(float)(N-1);

    thrust::device_vector<float> myvector(N);

    thrust::transform(thrust::make_counting_iterator(a/Dx),
                  thrust::make_counting_iterator((b+1.f)/Dx),
                  thrust::make_constant_iterator(Dx),
                  myvector.begin(),
                  thrust::multiplies<float>());

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

    getchar();

}

以上代码将返回:
0 3.870000
1 4.040526
2 4.211052
3 4.381579
4 4.552105
5 4.722631
6 4.893158
7 5.063684
8 5.234210
9 5.404737
10 5.575263
11 5.745790
12 5.916316
13 6.086842
14 6.257369
15 6.427895
16 6.598421
17 6.768948
18 6.939474
19 7.110000

完全如同linspace(3.87,7.11,20)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接