void scale(float a, float* x, int n) {
int i = block_idx * block_dim + thread_idx;
if (i < n) {
x[i] *= a;
}
}
void add(const float* x, const float* y, float* out, int n) {
int i = block_idx * block_dim + thread_idx;
if (i < n) {
out[i] = x[i] + y[i];
}
group.sync();
}
int main(void) {
const int N = 1 << 16;
float *dx = nullptr, *dy = nullptr, *dz = nullptr;
cudaMalloc((void**)&dx, N * sizeof(float));
cudaMalloc((void**)&dy, N * sizeof(float));
cudaMalloc((void**)&dz, N * sizeof(float));
cust::Stream() s1, s2;
cudaStreamCreate(&s1);
cudaStreamCreate(&s2);
cudaEvent_t e1, e2;
cudaEventCreate(&e1);
cudaEventCreate(&e2);
dim3 grid(N / 256);
dim3 block(256);
cudaMemcpyAsync(dx, dy, N * sizeof(float), cudaMemcpyDeviceToDevice, s1);
{ let _kernel = modules.get_function("scale"); unsafe { let _ = launch!( _kernel<<<grid as grid_size, block as block_size, 0 as usize, s1>>>(2.0f, dx, N) ); } };
cudaEventRecord(e1, s1);
cudaEventSynchronize(e1);
{ let _kernel = modules.get_function("add"); unsafe { let _ = launch!( _kernel<<<grid as grid_size, block as block_size, 128 as usize, s2>>>(dx, dy, dz, N) ); } };
cudaEventRecord(e2, s2);
cudaStreamSynchronize(s1);
cudaStreamSynchronize(s2);
cudaEventDestroy(e1);
cudaEventDestroy(e2);
cudaStreamDestroy(s1);
cudaStreamDestroy(s2);
cudaFree(dx);
cudaFree(dy);
cudaFree(dz);
return 0;
}