Sunday, August 30, 2009

Using constant_iterator

Thrust v1.1 introduces several new "fancy" iterators similar to those in the Boost Iterator Library. In this post we'll look at one named constant_iterator, which returns a constant value when dereferenced. constant_iterator is useful when you need a sequence filled with the same value, but don't want to store one explicitly in memory.

This first example creates a constant_iterator of type int with the value 10.

#include <thrust/iterator/constant_iterator.h>

thrust::constant_iterator<int> iter(10);

*iter; // returns 10
iter[0]; // returns 10
iter[1]; // returns 10
iter[13]; // returns 10

As you can see, iter mimics an infinite sequence of integers all with the value 10. While this behavior isn't all that exciting, it can be useful in practice. In the next example, we'll combine constant_iterator with transform to increment all elements in a sequence by a constant value.

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

int main(void)
{
thrust::device_vector<int> data(4);
data[0] = 3;
data[1] = 7;
data[2] = 2;
data[3] = 5;

// add 10 to all values in data
thrust::transform(data.begin(), data.end(),
thrust::constant_iterator<int>(10),
data.begin(),
thrust::plus<int>());

// data is now [13, 17, 12, 15]

return 0;
}


Note that we could have accomplished the same result by creating a temporary array and filling it with a constant value. However, this approach would have needlessly wasted
  • memory capacity - by storing the values explicitly in memory
  • memory bandwidth - by transferring values to and from memory
which is detrimental to scalability and performance. With fancy iterators we can make efficient use of memory without significant effort.

0 comments:

Post a Comment