# Using shared memory

**URL:** <https://forums.developer.nvidia.com/t/using-shared-memory/302834>\
**Category:** CUDA Programming and Performance\
**Created:** [August 9, 2024, 9:20am UTC](https://forums.developer.nvidia.com/t/using-shared-memory/302834 "2024-08-09T09:20:51Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![antony.bazir](https://developer.download.nvidia.com/images/forums/profile-default-devtalk-84.png) [@antony.bazir](https://forums.developer.nvidia.com/u/antony.bazir)\
**Post date:** [August 9, 2024, 9:20am UTC](https://forums.developer.nvidia.com/t/using-shared-memory/302834/1 "2024-08-09T09:20:51Z")

</div>

Hello, all

I’m using CUDA on a RTX 2000 Ada in order to parallelize some diffusion computations here is the C code for sequential calculation:

* * *

```auto
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

int main(int argc, char*argv[])
{

	int sz = 70;
	/*double *G *kG *DG;*/ 
	double r=20.0;
	double dx=20.0;
	int i,j,l;
	int h,t,nt;
	double time_taken;
	double dt =1e-4;  
	double* G, * kG, * DG, *G_r;
	clock_t start, end;
	FILE *ft,*fG,*ftt;

	G = malloc(sz*sz*sz*sizeof(double));
	G_r = malloc(sz*sz*sz*sizeof(double));
	kG = malloc(sz*sz*sz*sizeof(double));
	DG = malloc(sz*sz*sz*sizeof(double));
	

	/*files for results */
	ftt = fopen("time_seq.txt","w+");
	ft = fopen("Gt_seq.txt","w+");
	fG = fopen("G_seq.txt","w+");
		

	nt = 1/dt;
	/*initialising the grids*/
	for(l=0;l<sz;l++)
	{
		for(j=0;j<sz;j++)
		{
			for(i=0;i<sz;i++)
			{
				if((i-sz/2)*(i-sz/2)+(j-sz/2)*(j-sz/2)+(l-sz/2)*(l-sz/2)<r*r)
				{
					DG[i + j * sz + l * sz * sz] = 60000.0;
					kG[i + j * sz + l * sz * sz] = 1.0;
				}
				else
				{
					DG[i + j * sz + l * sz * sz] = 100000.0;
					kG[i + j * sz + l * sz * sz] = 0.0;
				}
					
				G[i + j * sz + l * sz * sz] = 5.0;
				G_r[i + j * sz + l * sz * sz] = 5.0;
			}
		}
	}

	start = clock();
	/*main loop*/
	for (h=0; h<nt; h++)
	{
		for(l=1;l<sz-1;l++)
		{
			for(j=1;j<sz-1;j++)
			{
				for(i=1;i<sz-1;i++)
				{
					G_r[i + j * sz + l * sz * sz] = G[i + j * sz + l * sz * sz] +
					dt*(DG[i+1 + j * sz + l * sz * sz] -DG[i-1 + j * sz + l * sz * sz])/(4*dx*dx)*(G[i+1 + j * sz + l * sz * sz] -G[i-1 + j * sz + l * sz * sz]) +
					dt*(DG[i + (j+1) * sz + l * sz * sz] -DG[i + (j-1) * sz + l * sz * sz])/(4*dx*dx)*(G[i + (j+1) * sz + l * sz * sz] -G[i + (j-1) * sz + l * sz * sz]) +
					dt*(DG[i + j * sz + (l+1) * sz * sz] -DG[i + j * sz + (l-1) * sz * sz])/(4*dx*dx)*(G[i + j * sz + (l+1) * sz * sz] -G[i + j * sz + (l-1) * sz * sz]) +
					dt/(dx*dx)*(DG[i + j * sz + l * sz * sz])*(G[i+1 + j * sz + l * sz * sz] -2*G[i + j * sz + l * sz * sz] + G[i-1 + j * sz + l * sz * sz]) +
					dt/(dx*dx)*(DG[i + j * sz + l * sz * sz])*(G[i + (j+1) * sz + l * sz * sz] -2*G[i + j * sz + l * sz * sz] + G[i + (j-1) * sz + l * sz * sz]) +
					dt/(dx*dx)*(DG[i + j * sz + l * sz * sz])*(G[i + j * sz + (l+1) * sz * sz] -2*G[i + j * sz + l * sz * sz] + G[i + j * sz + (l-1) * sz * sz]) -
					dt*kG[i + j * sz + l * sz * sz];

				}
			}

		}

		/*swapping new and current grid*/
		for (l = 0; l < sz; l++)
		{
			for (j = 0; j < sz; j++)
			{
				for (i = 0; i < sz; i++)
				{
					G[i + j * sz + l * sz * sz] = G_r[i + j * sz + l * sz * sz];

					if (h == nt - 1)
					{
						fprintf(fG, "%f \n", G[i + j * sz + l * sz * sz]);
					}
				}
			}
		}

		/*printing central value to file*/
		fprintf(ft,"%lf \n",G[sz/2 + sz/2 * sz + sz/2 * sz * sz]);
			
	}

	end = clock();
	time_taken = (double)(end - start) / (double)(CLOCKS_PER_SEC);
	printf("final value : %lf \n",G[sz / 2 + sz / 2 * sz + sz / 2 * sz * sz]);
	printf("Time taken is : %3.2lf sec \n",time_taken);
	fprintf(ftt,"%lf \n",time_taken);
	fclose(ft);
	fclose(fG);
	
	free(G);
	free(kG);
	free(DG);

}

```

* * *

When compiled on windows 11 with this command :

```auto
nvcc -O2 -o FD3D_seq FD3D_seq.c

```

it does the computation in 29.2 seconds

I have done parallelization with CUDA with this code :

```auto
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

// Kernel definition
__global__ void run_diff(double* G, double* kG, double* DG, double* G_r, int sz, double dx, double dt)
{
	int i, j, l;
	i = blockIdx.x * blockDim.x + threadIdx.x;
	j = blockIdx.y * blockDim.y + threadIdx.y;
	l = blockIdx.z * blockDim.z + threadIdx.z;

	//printf("G_ctr: %lf \n", G[sz/2 + sz/2*sz + sz/2*sz*sz]);

	if (i < sz - 1 && j < sz - 1 && l < sz - 1 && i>0 && j>0 && l>0)
	{
		G_r[i + j * sz + l * sz * sz] = G[i + j * sz + l * sz * sz] +
			dt * (DG[i + 1 + j * sz + l * sz * sz] - DG[i - 1 + j * sz + l * sz * sz]) / (4 * dx * dx) * (G[i + 1 + j * sz + l * sz * sz] - G[i - 1 + j * sz + l * sz * sz]) +
			dt * (DG[i + (j + 1) * sz + l * sz * sz] - DG[i + (j - 1) * sz + l * sz * sz]) / (4 * dx * dx) * (G[i + (j + 1) * sz + l * sz * sz] - G[i + (j - 1) * sz + l * sz * sz]) +
			dt * (DG[i + j * sz + (l + 1) * sz * sz] - DG[i + j * sz + (l - 1) * sz * sz]) / (4 * dx * dx) * (G[i + j * sz + (l + 1) * sz * sz] - G[i + j * sz + (l - 1) * sz * sz]) +
			dt / (dx * dx) * (DG[i + j * sz + l * sz * sz]) * (G[i + 1 + j * sz + l * sz * sz] - 2 * G[i + j * sz + l * sz * sz] + G[i - 1 + j * sz + l * sz * sz]) +
			dt / (dx * dx) * (DG[i + j * sz + l * sz * sz]) * (G[i + (j + 1) * sz + l * sz * sz] - 2 * G[i + j * sz + l * sz * sz] + G[i + (j - 1) * sz + l * sz * sz]) +
			dt / (dx * dx) * (DG[i + j * sz + l * sz * sz]) * (G[i + j * sz + (l + 1) * sz * sz] - 2 * G[i + j * sz + l * sz * sz] + G[i + j * sz + (l - 1) * sz * sz]) -
			dt * kG[i + j * sz + l * sz * sz];
	}
}

__global__ void swap(double* G, double* G_r, int sz)
{

	int i, j, l;
	i = blockIdx.x * blockDim.x + threadIdx.x;
	j = blockIdx.y * blockDim.y + threadIdx.y;
	l = blockIdx.z * blockDim.z + threadIdx.z;
	//put G_r in G
	G[i + j * sz + l * sz * sz] = G_r[i + j * sz + l * sz * sz];
}

__global__ void ctr(double* G_ctr, double *G, int h, int sz)
{
	//put G_r in G
	G_ctr[h] = G[sz / 2 + sz / 2 * sz + sz / 2 * sz * sz];
}

int main(int argc, char*argv[])
{

	int sz = 70;
	/*double *G *kG *DG;*/ 
	double r=20.0;
	double dx=20.0;
	int i,j,l;
	int h,nt;
	double time_taken;
	double dt = 1e-4;
	double* G, * kG, * DG, * G_r;
	double *G_ctr;
	double* d_G, * d_kG, * d_DG, * d_G_r, d_sz, d_dx, d_dt, *d_G_ctr;
	int device;
	cudaDeviceProp prop;
	clock_t start, end;
	FILE *f,*ft,*fG,*ftt;

	//open files
	f = fopen("devc_diff", "w+");
	ftt = fopen("time_cuda.txt", "w+");
	ft = fopen("Gt_cuda.txt", "w+");
	fG = fopen("G_cuda.txt", "w+");

	//Get device properties
	cudaGetDevice(&device);
	cudaGetDeviceProperties(&prop, device);
	cudaSetDevice(device);
	fprintf(f, "Device %d (%s) has compute capability %d.%d.\n",
	device, prop.name, prop.major, prop.minor);

	
	// Allocate space for device 
	cudaMalloc((void**)&d_G, sz * sz * sz * sizeof(double));
	cudaMalloc((void**)&d_kG, sz * sz * sz * sizeof(double));
	cudaMalloc((void**)&d_DG, sz * sz * sz * sizeof(double));
	cudaMalloc((void**)&d_G_r, sz * sz * sz * sizeof(double));

	// Alloc space for host 
	G = (double*)malloc(sz * sz * sz * sizeof(double));
	G_r = (double*)malloc(sz * sz * sz * sizeof(double));
	kG = (double*)malloc(sz * sz * sz * sizeof(double));
	DG = (double*)malloc(sz * sz * sz * sizeof(double));
	cudaMalloc((void**)&d_G_ctr, nt * sizeof(double));
	G_ctr = (double*)malloc(nt * sizeof(double));

	
	nt = 1 / dt;

	/*initialising the grids*/
	/*int (*arr)[M] = malloc(sizeof(int[N][M]));*/

	for(l=0;l<sz;l++)
	{
		for(j=0;j<sz;j++)
		{
			for(i=0;i<sz;i++)
			{
				if((i-sz/2)*(i-sz/2)+(j-sz/2)*(j-sz/2)+(l-sz/2)*(l-sz/2)<r*r)
				{
					DG[i + j * sz + l * sz * sz] = 60000.0;
					kG[i + j * sz + l * sz * sz] = 1.0;
				}
				else
				{
					DG[i + j * sz + l * sz * sz] = 100000.0;
					kG[i + j * sz + l * sz * sz] = 0.0;
				}
					
				G[i + j * sz + l * sz * sz] = 5.0;
				G_r[i + j * sz + l * sz * sz] = 5.0;
				/*fprintf(fG,"%lf \n",kG[i][j][l]);*/
			}
		}
	}

	//start timing 
	start = clock();

	// Copy inputs to device
	cudaMemcpy(d_G, G, sz*sz*sz*sizeof(double), cudaMemcpyHostToDevice);
	cudaMemcpy(d_kG, kG, sz*sz*sz * sizeof(double), cudaMemcpyHostToDevice);
	cudaMemcpy(d_DG, DG, sz*sz*sz * sizeof(double), cudaMemcpyHostToDevice);
	cudaMemcpy(d_G_r, G_r, sz*sz*sz * sizeof(double), cudaMemcpyHostToDevice);
	cudaMemcpy(&d_sz, &sz, sizeof(int), cudaMemcpyHostToDevice);
	cudaMemcpy(&d_dx, &dx, sizeof(double), cudaMemcpyHostToDevice);
	cudaMemcpy(&d_dt, &dt, sizeof(double), cudaMemcpyHostToDevice);

	for (h=0; h<nt; h++)
	{
		//threads and blocks 
		dim3 threadsPerBlock(5, 5, 5);
		dim3 numBlocks(sz / threadsPerBlock.x, sz / threadsPerBlock.y, sz / threadsPerBlock.z);

		//solving for one step
		run_diff<<<numBlocks, threadsPerBlock>>>(d_G, d_kG, d_DG, d_G_r, sz, dx, dt);
		swap<<<numBlocks, threadsPerBlock>>>(d_G, d_G_r, sz);
		ctr<<<1, 1>>>(d_G_ctr,d_G, h, sz);
			
	}

	//copy back to host
	cudaMemcpy(G_ctr, d_G_ctr, nt*sizeof(double), cudaMemcpyDeviceToHost);
	cudaMemcpy(G, d_G, sz*sz*sz*sizeof(double), cudaMemcpyDeviceToHost);

	//stop timing 
	end = clock();

	//writing to files
	for (h = 0; h < nt; h++)
	{
		fprintf(ft, "%lf \n", G_ctr[h]);
	}

	for (l = 0; l < sz; l++)
	{
		for (j = 0; j < sz; j++)
		{
			for (i = 0; i < sz; i++)
			{
				fprintf(fG, "%f \n", G[i + j * sz + l * sz * sz]);
			}
		}
	}

	
	time_taken = (double)(end - start) / (double)(CLOCKS_PER_SEC);
	printf("final value : %lf \n",G[sz / 2 + sz / 2 * sz + sz / 2 * sz * sz]);
	printf("Time taken is : %3.2lf sec \n",time_taken);
	fprintf(ftt,"%lf \n",time_taken);
	
	//clean
	fclose(f);
	fclose(ftt);
	fclose(ft);
	fclose(fG);
		
	free(G);
	free(kG);
	free(DG);
	free(G_ctr);

	cudaFree(d_G); 
	cudaFree(d_kG); 
	cudaFree(d_DG); 
	cudaFree(d_G_r);
	cudaFree(d_G_ctr);

	

}

```

which I compiled with

```auto
nvcc -O2 -o FD3D_cuda FD3D_cuda.cu

```

The code works and does the calculation with no differences in the results in 4.1 seconds. but I felt like the GPU usage was never high (as if I was not using its full capacity at all) so I wondered if was not optimizing to the maximum. (for reference a 32 threads calculation with OpenMP performed the whole calculation in 9.5 seconds)

I checked the documentation and found the section on “shared memory” (3.2.3 Cuda C programming guide) and tried to rewrite my code in order to use shared memory based on the matrix multiplication example given in the documentation. I ended up with this code :

```auto
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
//trying to optimize with shared memory
// 
// Kernel definition

#define BLOCK_SIZE 5

__device__ void swap(double* G, double* G_r, int sz)
{

	int i, j, l;
	i = blockIdx.x * blockDim.x + threadIdx.x;
	j = blockIdx.y * blockDim.y + threadIdx.y;
	l = blockIdx.z * blockDim.z + threadIdx.z;
	//put G_r in G
	G[i + j * sz + l * sz * sz] = G_r[i + j * sz + l * sz * sz];
}

__device__ void Sub_grid(double* sG, double* iG, int blockRow, int blockCol, int blockStck, int sz)
{
	int i, j, l;
	i = threadIdx.x;
	j = threadIdx.y;
	l = threadIdx.z;

	//rims 
	sG[(0) + (j + 1) * (blockDim.x + 2) + (l + 1) * (blockDim.x + 2) * (blockDim.y + 2)] = iG[(blockRow * blockDim.x) + (blockCol * blockDim.y + j) * sz + (blockStck * blockDim.z + l) * (sz) * (sz)];
	sG[(blockDim.x + 1) + (j + 1) * (blockDim.x + 2) + (l + 1) * (blockDim.x + 2) * (blockDim.y + 2)] = iG[(blockRow * blockDim.x + blockDim.x + 1) + (blockCol * blockDim.y + j) * sz + (blockStck * blockDim.z + l) * (sz) * (sz)];
	sG[(i + 1) + (0) * (blockDim.x + 2) + (l + 1) * (blockDim.x + 2) * (blockDim.y + 2)] = iG[(blockRow * blockDim.x + i) + (blockCol * blockDim.y) * sz + (blockStck * blockDim.z + l) * (sz) * (sz)];
	sG[(i + 1) + (blockDim.y + 1) * (blockDim.x + 2) + (l + 1) * (blockDim.x + 2) * (blockDim.y + 2)] = iG[(blockRow * blockDim.x + i) + (blockCol * blockDim.y + (blockDim.y + 1)) * sz + (blockStck * blockDim.z + l) * (sz) * (sz)];
	sG[(i + 1) + (j + 1) * (blockDim.x + 2) + (0) * (blockDim.x + 2) * (blockDim.y + 2)] = iG[(blockRow * blockDim.x + i) + (blockCol * blockDim.y + j) * sz + (blockStck * blockDim.z) * (sz) * (sz)];
	sG[(i + 1) + (j + 1) * (blockDim.x + 2) + (blockDim.z + 1) * (blockDim.x + 2) * (blockDim.y + 2)] = iG[(blockRow * blockDim.x + i) + (blockCol * blockDim.y + j) * sz + (blockStck * blockDim.z + (blockDim.z + 1)) * (sz) * (sz)];

	//bulk
	sG[(i + 1) + (j + 1) * (blockDim.x + 2) + (l + 1) * (blockDim.x + 2) * (blockDim.y + 2)] = iG[(blockRow * blockDim.x + i) + (blockCol * blockDim.y + j) * sz + (blockStck * blockDim.z + l) * (sz) * (sz)];
}

__global__ void run_diff(double* G, double* kG, double* DG, double* G_r, int sz, double dx, double dt)
{
	int i, j, l;
	int si, sj, sl;
	i = blockIdx.x * blockDim.x + threadIdx.x;
	j = blockIdx.y * blockDim.y + threadIdx.y;
	l = blockIdx.z * blockDim.z + threadIdx.z;

	//shared memory grids
	__shared__ double G_s[(BLOCK_SIZE + 2) * (BLOCK_SIZE + 2) * (BLOCK_SIZE + 2)];
	__shared__ double D_s[(BLOCK_SIZE + 2) * (BLOCK_SIZE + 2) * (BLOCK_SIZE + 2)];
	__shared__ double k_s[(BLOCK_SIZE + 2) * (BLOCK_SIZE + 2) * (BLOCK_SIZE + 2)];
	__shared__ double dt_s;
	__shared__ double dx_s;
	__shared__ int sz_s;

	si = threadIdx.x;
	sj = threadIdx.y;
	sl = threadIdx.z;

	//load the sub grids 
	Sub_grid(G_s,G, blockIdx.x, blockIdx.y, blockIdx.z,sz);
	Sub_grid(D_s,DG, blockIdx.x, blockIdx.y, blockIdx.z, sz);
	Sub_grid(k_s,kG, blockIdx.x, blockIdx.y, blockIdx.z, sz);

	__syncthreads();

	
	if (i < sz - 1 && j < sz - 1 && l < sz - 1 && i>0 && j>0 && l>0)
	{
		if(si<(blockDim.x+1)&&sj<(blockDim.y+1)&&sl<(blockDim.z+1))
			G_r[i + j * sz + l * sz * sz] = G_s[(si+1) + (sj + 1) * (blockDim.x+2) + (sl + 1) * (blockDim.x+2) * (blockDim.y+2)] +
				dt * (D_s[(si+1) + 1 + (sj + 1) * (blockDim.x+2) + (sl + 1) * (blockDim.x+2) * (blockDim.y+2)] - D_s[(si+1) - 1 + (sj + 1) * (blockDim.x+2) + (sl + 1) * (blockDim.x+2) * (blockDim.y+2)]) / (4 * dx * dx) * (G_s[(si+1) + 1 + (sj + 1) * (blockDim.x+2) + (sl + 1) * (blockDim.x+2) * (blockDim.y+2)] - G_s[(si+1) - 1 + (sj + 1) * (blockDim.x+2) + (sl + 1) * (blockDim.x+2) * (blockDim.y+2)]) +
				dt * (D_s[(si+1) + ((sj + 1) + 1) * (blockDim.x+2) + (sl + 1) * (blockDim.x+2) * (blockDim.y+2)] - D_s[(si+1) + ((sj + 1) - 1) * (blockDim.x+2) + (sl + 1) * (blockDim.x+2) * (blockDim.y+2)]) / (4 * dx * dx) * (G_s[(si+1) + ((sj + 1) + 1) * (blockDim.x+2) + (sl + 1) * (blockDim.x+2) * (blockDim.y+2)] - G_s[(si+1) + ((sj + 1) - 1) * (blockDim.x+2) + (sl + 1) * (blockDim.x+2) * (blockDim.y+2)]) +
				dt * (D_s[(si+1) + (sj + 1) * (blockDim.x+2) + ((sl + 1) + 1) * (blockDim.x+2) * (blockDim.y+2)] - D_s[(si+1) + (sj + 1) * (blockDim.x+2) + ((sl + 1) - 1) * (blockDim.x+2) * (blockDim.y+2)]) / (4 * dx * dx) * (G_s[(si+1) + (sj + 1) * (blockDim.x+2) + ((sl + 1) + 1) * (blockDim.x+2) * (blockDim.y+2)] - G_s[(si+1) + (sj + 1) * (blockDim.x+2) + ((sl + 1) - 1) * (blockDim.x+2) * (blockDim.y+2)]) +
				dt / (dx_s * dx_s) * (D_s[(si+1) + (sj + 1) * (blockDim.x+2) + (sl + 1) * (blockDim.x+2) * (blockDim.y+2)]) * (G_s[(si+1) + 1 + (sj + 1) * (blockDim.x+2) + (sl + 1) * (blockDim.x+2) * (blockDim.y+2)] - 2 * G_s[(si+1) + (sj + 1) * (blockDim.x+2) + (sl + 1) * (blockDim.x+2) * (blockDim.y+2)] + G_s[(si+1) - 1 + (sj + 1) * (blockDim.x+2) + (sl + 1) * (blockDim.x+2) * (blockDim.y+2)]) +
				dt / (dx_s * dx_s) * (D_s[(si+1) + (sj + 1) * (blockDim.x+2) + (sl + 1) * (blockDim.x+2) * (blockDim.y+2)]) * (G_s[(si+1) + ((sj + 1) + 1) * (blockDim.x+2) + (sl + 1) * (blockDim.x+2) * (blockDim.y+2)] - 2 * G_s[(si+1) + (sj + 1) * (blockDim.x+2) + (sl + 1) * (blockDim.x+2) * (blockDim.y+2)] + G_s[(si+1) + ((sj + 1) - 1) * (blockDim.x+2) + (sl + 1) * (blockDim.x+2) * (blockDim.y+2)]) +
				dt / (dx_s * dx_s) * (D_s[(si+1) + (sj + 1) * (blockDim.x+2) + (sl + 1) * (blockDim.x+2) * (blockDim.y+2)]) * (G_s[(si+1) + (sj + 1) * (blockDim.x+2) + ((sl + 1) + 1) * (blockDim.x+2) * (blockDim.y+2)] - 2 * G_s[(si+1) + (sj + 1) * (blockDim.x+2) + (sl + 1) * (blockDim.x+2) * (blockDim.y+2)] + G_s[(si+1) + (sj + 1) * (blockDim.x+2) + ((sl + 1) - 1) * (blockDim.x+2) * (blockDim.y+2)]) -
				dt * k_s[(si+1) + (sj + 1) * (blockDim.x+2) + (sl + 1) * (blockDim.x+2) * (blockDim.y+2)];
	}

	__syncthreads();
	

	swap(G, G_r, sz);
	
}

__global__ void ctr(double* G_ctr, double *G, int h, int sz)
{
	//put G in G_ctr
	G_ctr[h] = G[sz / 2 + sz / 2 * sz + sz / 2 * sz * sz];
}

int main(int argc, char*argv[])
{

	int sz = 70;
	/*double *G *kG *DG;*/ 
	double r=20.0;
	double dx=20.0;
	int i,j,l;
	int h,nt;
	double time_taken;
	double dt=1e-4;
	double* G, * kG, * DG, * G_r;
	double *G_ctr;
	double* d_G, * d_kG, * d_DG, * d_G_r, d_sz, d_dx, d_dt, *d_G_ctr;
	int device;
	cudaDeviceProp prop;
	clock_t start, end;
	FILE *f,*ft,*fG,*ftt;

	f = fopen("devc_diff_2", "w+");

	//Get device properties
	cudaGetDevice(&device);
	cudaGetDeviceProperties(&prop, device);
	cudaSetDevice(device);
	fprintf(f, "Device %d (%s) has compute capability %d.%d.\n",
		device, prop.name, prop.major, prop.minor);

		
	ftt = fopen("time_cuda_shared_mem.txt","w+");
	ft = fopen("Gt_cuda_shared_mem.txt", "w+");
	fG = fopen("G1_cuda_shared_mem.txt", "w+");

	// Allocate space for device 
	cudaMalloc((void**)&d_G, sz * sz * sz * sizeof(double));
	cudaMalloc((void**)&d_kG, sz * sz * sz * sizeof(double));
	cudaMalloc((void**)&d_DG, sz * sz * sz * sizeof(double));
	cudaMalloc((void**)&d_G_r, sz * sz * sz * sizeof(double));

	// Alloc space for host
	G = (double*)malloc(sz * sz * sz * sizeof(double));
	G_r = (double*)malloc(sz * sz * sz * sizeof(double));
	kG = (double*)malloc(sz * sz * sz * sizeof(double));
	DG = (double*)malloc(sz * sz * sz * sizeof(double));

	nt = 1 / dt;
	cudaMalloc((void**)&d_G_ctr, nt*sizeof(double));
	G_ctr = (double*)malloc(nt * sizeof(double));

	for(l=0;l<sz;l++)
	{
		for(j=0;j<sz;j++)
		{
			for(i=0;i<sz;i++)
			{
				if((i-sz/2)*(i-sz/2)+(j-sz/2)*(j-sz/2)+(l-sz/2)*(l-sz/2)<r*r)
				{
					DG[i + j * sz + l * sz * sz] = 60000.0;
					kG[i + j * sz + l * sz * sz] = 1.0;
				}
				else
				{
					DG[i + j * sz + l * sz * sz] = 100000.0;
					kG[i + j * sz + l * sz * sz] = 0.0;
				}
					
				G[i + j * sz + l * sz * sz] = 5.0;
				G_r[i + j * sz + l * sz * sz] = 5.0;
				
			}
		}
	}

	//start timing 
	start = clock();

	// Copy inputs to device
	cudaMemcpy(d_G, G, sz*sz*sz*sizeof(double), cudaMemcpyHostToDevice);
	cudaMemcpy(d_kG, kG, sz*sz*sz * sizeof(double), cudaMemcpyHostToDevice);
	cudaMemcpy(d_DG, DG, sz*sz*sz * sizeof(double), cudaMemcpyHostToDevice);
	cudaMemcpy(d_G_r, G_r, sz*sz*sz * sizeof(double), cudaMemcpyHostToDevice);
	cudaMemcpy(&d_sz, &sz, sizeof(int), cudaMemcpyHostToDevice);
	cudaMemcpy(&d_dx, &dx, sizeof(double), cudaMemcpyHostToDevice);
	cudaMemcpy(&d_dt, &dt, sizeof(double), cudaMemcpyHostToDevice);

	for (h=0; h<nt; h++)
	{
		//threads and blocks
		dim3 threadsPerBlock(BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE);
		dim3 numBlocks(sz / threadsPerBlock.x, sz / threadsPerBlock.y, sz / threadsPerBlock.z);
	

		run_diff<<<numBlocks, threadsPerBlock>>>(d_G, d_kG, d_DG, d_G_r, sz, dx, dt);
		ctr<<<1, 1>>>(d_G_ctr,d_G, h, sz);
			
	}

	//copy back to host
	cudaMemcpy(G_ctr, d_G_ctr, nt*sizeof(double), cudaMemcpyDeviceToHost);
	cudaMemcpy(G, d_G, sz * sz * sz * sizeof(double), cudaMemcpyDeviceToHost);

	end = clock();

	//print to files
	for (h = 0; h < nt; h++)
	{
		fprintf(ft, "%lf \n", G_ctr[h]);
	}

	for (l = 0; l < sz; l++)
	{
		for (j = 0; j < sz; j++)
		{
			for (i = 0; i < sz; i++)
			{
				fprintf(fG, "%f \n", G[i + j * sz + l * sz * sz]);
			}
		}
	}

		

	
	time_taken = (double)(end - start) / (double)(CLOCKS_PER_SEC);
	printf("final value : %lf \n",G[sz / 2 + sz / 2 * sz + sz / 2 * sz * sz]);
	printf("Time taken is : %3.2lf sec \n",time_taken);
	fprintf(ftt,"%lf \n",time_taken);

	
	//clean 
	fclose(ft);
	fclose(ftt);
	fclose(f);
	fclose(fG);
		
	free(G);
	free(kG);
	free(DG);
	free(G_ctr);

	cudaFree(d_G); 
	cudaFree(d_kG); 
	cudaFree(d_DG); 
	cudaFree(d_G_r);
	cudaFree(d_G_ctr);

}

```

compiled with

```auto
nvcc -O2 -o FD3D_cuda_shared_mem FD3D_cuda_shared_mem.cu

```

This code ran in 3.28 secs and yielded a different final value (4.808483 vs4.33084)  
This yields two questions

1. Should I expect further improvement on this kind of calculation with shared memory or any other implementation provided by CUDA, or is my second code (CUDA w/o shared memory) already close to the best I can get ?

2. If significant improvement is possible with shared memory, can anybody help me with the code ?

Sorry for the long post  
Thanks

---

<div class="post-metadata">

**Author:** ![Curefab](https://developer.download.nvidia.com/images/forums/profile-default-devtalk-84.png) [@Curefab](https://forums.developer.nvidia.com/u/Curefab)\
**Post date:** [August 9, 2024, 12:19pm UTC](https://forums.developer.nvidia.com/t/using-shared-memory/302834/2 "2024-08-09T12:19:10Z")

</div>

> [@antony.bazir](#):
>
> yielded a different final value (4.808483 vs4.33084)

Can you check, whether this is just due to rounding errors (even when using double) or an error in the code? You are using 10000 iterations, perhaps you could print out and check intermediate results. And if there is a deviation in all or a specific iteration, just look at one iteration and find out, how the value is computed? It could be due to the boundaries of your shared memory sub-regions.

You can run Compute Nsight to better estimate the potential for further optimization. It shows the current bottleneck and how much your memory bandwidth and compute units are filled.

The double speed of many Nvidia GPUs are not very good. On a budget you would get much faster results on a used P100 GPU for 250 to 300 USD (or a new A100 or H100 also on a - better/higher - budget).

BTW why would you do the swap explicitly? Just exchange pointers to the two memory regions.

For fuller optimization, consider, if you can do several iterations within shared memory sub-regions before copying back to the global memory. The boundaries could be overlapping with doing the same work for the overlapping regions twice, but that would probably not matter, if the regions are large enough.

Try to avoid divisions, make some parameters to compile-time constants, e.g. dx could be a template parameter of the kernel function instead of an actual parameter. If you want to change the parameter dynamically (e.g. user input), you could select between different pre-compiled kernels with different dx parameters.

---

<div class="post-metadata">

**Author:** ![antony.bazir](https://developer.download.nvidia.com/images/forums/profile-default-devtalk-84.png) [@antony.bazir](https://forums.developer.nvidia.com/u/antony.bazir)\
**Post date:** [August 9, 2024, 2:55pm UTC](https://forums.developer.nvidia.com/t/using-shared-memory/302834/3 "2024-08-09T14:55:43Z")

</div>

For the difference I’ll have a closer look at indexes.

I tried to do the swap directly in the sequential code by swapping the whole loop with :

G = G\_r;

But this yielded a different results from the explicit swap.

I also tried to move the time loop within device code in the first cuda code (w/o shared memory) which did not work at all.

I’ll look into compute Nsight and let you know if I make progress

Thanks

---

<div class="post-metadata">

**Author:** ![Curefab](https://developer.download.nvidia.com/images/forums/profile-default-devtalk-84.png) [@Curefab](https://forums.developer.nvidia.com/u/Curefab)\
**Post date:** [August 9, 2024, 5:39pm UTC](https://forums.developer.nvidia.com/t/using-shared-memory/302834/4 "2024-08-09T17:39:51Z")

</div>

> [@antony.bazir](#):
>
> G = G\_r;

With this instruction you are not copying memory (which is good), but just copying the pointer to memory.  
But afterwards `G` and `G_r` point to the same memory address. You should rather a) swap `G` and `G_r`, either by a1)`std::swap` or by a2) using a temp pointer or b) by making your loop with two phases/iterations:

Either b1)

```auto
		run_diff<<<numBlocks, threadsPerBlock>>>(d_G, d_kG, d_DG, d_G_r, sz, dx, dt); // phase 0
		run_diff<<<numBlocks, threadsPerBlock>>>(d_G_r, d_kG, d_DG, d_G, sz, dx, dt); // phase 1

```

or b2)

```auto
		run_diff<<<numBlocks, threadsPerBlock>>>((h & 1) ? d_G_r : d_G), d_kG, d_DG, (h & 1) ? d_G : d_G_r), sz, dx, dt);

```
