我有困难理解CUDA的thrust库中的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...
在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。
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)
。