#include <hip/hip_runtime.h>
__global__ void scale(float a, float* x, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) {
x[i] *= a;
}
}
__global__ void add(const float* x, const float* y, float* out, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) {
out[i] = x[i] + y[i];
}
__syncthreads();
}
int main(void) {
const int N = 1 << 16;
float *dx = nullptr, *dy = nullptr, *dz = nullptr;
hipMalloc((void**)&dx, N * sizeof(float));
hipMalloc((void**)&dy, N * sizeof(float));
hipMalloc((void**)&dz, N * sizeof(float));
hipStream_t() s1, s2;
hipStreamCreate(&s1);
hipStreamCreate(&s2);
hipEvent_t() e1, e2;
hipEventCreate(&e1);
hipEventCreate(&e2);
dim3 grid(N / 256);
dim3 block(256);
hipMemcpyAsync(dx, dy, N * sizeof(float), cudaMemcpyDeviceToDevice, s1);
hipLaunchKernelGGL(scale, dim3(grid), dim3(block), 0, s1, 2.0f, dx, N);
hipEventRecord(e1, s1);
hipEventSynchronize(e1);
hipLaunchKernelGGL(add, dim3(grid), dim3(block), 128, s2, dx, dy, dz, N);
hipEventRecord(e2, s2);
hipStreamSynchronize(s1);
hipStreamSynchronize(s2);
hipEventDestroy(e1);
hipEventDestroy(e2);
hipStreamDestroy(s1);
hipStreamDestroy(s2);
hipFree(dx);
hipFree(dy);
hipFree(dz);
return 0;
}