How do I get CUDA kernels running in visual studio?

DanielG 0 Reputation points
2024-07-21T22:51:08.3366667+00:00

Hello-

I'm just starting to learn CUDA programming. I wrote a program that simply adds up two arrays and then checks the sum of the arrays for errors. It works fine without CUDA. When I add in the code to run the "add" function on the GPU, the function does not appear to get called. The program compiles fine and runs, but the output is incorrect. I added in all the visual studio CUDA extensions. The add function is called with "add<<<1, 1>>>(N, x, y);".

Can anyone help me out? Below is the code. I'm a running a Quadro RTX 4000.

Thanks in advance.

#include<iostream>

#include<math.h>

#include<cuda.h>

#include<cuda_runtime.h>

#include<device_launch_parameters.h>

global void add(int n, float *x, float *y)

{

for (int i = 0; i < n; i++)

	y[i] = x[i] + y[i];

}

int main(void) {

int N = 1 << 20;

float* x, * y;


// Allocate unified memory - accessible from the CPU or GPU

cudaMallocManaged(&x, N * sizeof(float));

cudaMallocManaged(&y, N * sizeof(float));


//initialize x and y arrays on the host

for (int i = 0; i < N; i++) {

	x[i] = 1.0f;

	y[i] = 2.0f;

}


// Run kernel on 1M elements on the GPU

add<<<1, 1>>>(N, x, y);


// Wait for the GPU to finish before accessing the data

cudaDeviceSynchronize();


// Check for errors (all values should be 3.0f)

float maxError = 0.0f;

for (int i = 0; i < N; i++)

	maxError = fmax(maxError, fabs(y[i] - 3.0f));

std::cout << "Max error: " << maxError << std::endl;

std::cout << y[0] << std::endl;

// Free memory

cudaFree(x);

cudaFree(y);

return 0;

}

Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
5,093 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Tianyu Sun-MSFT 30,556 Reputation points Microsoft Vendor
    2024-07-22T09:46:40.5766667+00:00

    Hello @DanielG,

    Thank you for taking time to post this issue in Microsoft Q&A forum.

    As your question is more related to CUDA programming, please kindly post your question on CUDA forum for better help.

    Thanks for your understanding, have a nice day:)

    Best Regards,

    Tianyu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.