gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 23:57:02 25 4
gpt4 key购买 nike

我无法理解 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com