【发布时间】:2016-01-14 00:38:25
【问题描述】:
我正在调用一个 cuda 代码来获取每个键的所有值的总和。 目的是通过并行操作来减少reducer所花费的时间。 但是,reducer 中的值是 IntWritable 形式。因此,我必须将它们转换为整数数组以传递给 cuda 代码。 这是我的减速器代码:
public static class IntSumReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
private IntWritable result = new IntWritable();
public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
List<Integer> numbers = new ArrayList<Integer>();
for(IntWritable val : values)
numbers.add(val.get());
}
int[] ret = ArrayUtils.toPrimitive(numbers.toArray(new Integer[numbers.size()]));
result.set(Main.sumNumbers(ret));
context.write(key,result);
}
}
问题在于,为了将 IntWritable 转换为 Integer 数组,我必须遍历每个作为串行操作的值。因此,它正在增加更多的时间。 那么,有什么方法可以让我不必遍历每个值并直接转换为 int 数组?
这是映射器代码:
public static class TokenizerMapper extends
Mapper<Object, Text, Text, IntWritable> {
private final static IntWritable one = new IntWritable(1);
private Text word = new Text();
public void map(Object key, Text value, Context context)
throws IOException, InterruptedException {
StringTokenizer itr = new StringTokenizer(value.toString());
while (itr.hasMoreTokens()) {
word.set(itr.nextToken());
context.write(word, one);
}
}
}
这是我的 cuda 代码:
#include <stdio.h>
#ifndef _ADDARRAY_KERNEL_H_
#define _ADDARRAY_KERNEL_H_
#ifdef __cplusplus
extern "C"
{
#endif
__global__ void add_array(int *a, int *c, int N)
{
*c = 0;
int i;
for(i = 0; i<N;i++)
{
*c = *c + a[i];
}
}
#ifdef __cplusplus
}
#endif
#endif // #ifndef _ADDARRAY_KERNEL_H_
#ifdef __cplusplus
extern "C"
{
#endif
int cuda_sum(int *a_h, int N)
{
int *a_d, c=0;
int *dev_c;
cudaMalloc((void**)&dev_c, sizeof(int));
size_t size = N * sizeof (int);
// a_h = (int *) malloc(size);
cudaMalloc((void **) & a_d, size);
cudaMemcpy(a_d, a_h, size, cudaMemcpyHostToDevice);
add_array <<<1, 1 >>>(a_d, dev_c, N);
cudaMemcpy(&c, dev_c, sizeof(int), cudaMemcpyDeviceToHost);
cudaFree(dev_c);
return c;
}
#ifdef __cplusplus
}
#endif
谢谢
【问题讨论】:
-
您能否分享一个“cuda 代码”的链接,它是一个添加数字更有效的库吗?我假设您可以使用内置的 IntSumReducer
-
cuda 代码将创建一个自定义库以有效地添加数字
-
你能给我这个图书馆的链接吗?然后@Pradyumna 的回复似乎还可以。
-
看,我正在创建一个扩展名为 .so 的 cuda 库。该库使用内核调用对所有整数求和。 (就像任何 cuda 代码中的简单添加操作一样)。所以,我需要给一个整数数组作为这个 cuda 库的输入。
-
已经提供的答案有什么不足吗?