Skip to content

Instantly share code, notes, and snippets.

@zhaofeng-shu33
Last active November 10, 2019 03:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhaofeng-shu33/deed18394dd0256508bc3b2d470a25fe to your computer and use it in GitHub Desktop.
Save zhaofeng-shu33/deed18394dd0256508bc3b2d470a25fe to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <cuda.h>
#define check( a ) \
{\
if ( (a) != 0 ) {\
printf("ERROR in %s : %d\n", __FILE__ , __LINE__ );\
exit(0);\
}\
}
__global__ void calculate_degree(int m, int* dev_edges, int* dev_nodes){
int from = blockDim.x * blockIdx.x + threadIdx.x;
int step = gridDim.x * blockDim.x;
for (int i = from; i < m; i += step) {
int prev = dev_edges[2 * i];
int next = dev_edges[2 * i + 1];
atomicAdd(dev_nodes + prev, 1);
atomicAdd(dev_nodes + next, 1);
}
}
int main(){
int n = 4;
int m = 5;
int edges[] = {0, 1, 1, 2, 2, 3, 3, 1, 2, 0};
int nodes[] = {0, 0, 0, 0};
int* dev_edges;
int* dev_nodes;
check(cudaMalloc(&dev_edges, 2 * m * sizeof(int)));
check(cudaMalloc(&dev_nodes, n * sizeof(int)));
check(cudaMemcpy(dev_edges, edges, 2 * m * sizeof(int), cudaMemcpyHostToDevice));
check(cudaMemcpy(dev_nodes, nodes, n * sizeof(int), cudaMemcpyHostToDevice));
calculate_degree<<<1, 256>>>(m, dev_edges, dev_nodes);
check(cudaMemcpy(nodes, dev_nodes, n * sizeof(int), cudaMemcpyDeviceToHost));
for (int i = 0; i < 4; i++) {
printf("Node %d: degree %d\n", i, nodes[i]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment