Shared Code

by k.manoj2522005·19 views·Oct 16, 2026Open in Playground →
main.cu
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <curand_kernel.h>
#include <cuda_runtime.h>

#define BLOCK_SIZE 256

// ============================================================
// CUDA Kernel
// Each thread performs one Monte Carlo simulation
// ============================================================
__global__ void monteCarloKernel(
    double *payoffs,
    int numSimulations,
    double S0,
    double K,
    double r,
    double sigma,
    double T,
    unsigned long seed
) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;

    if (i >= numSimulations)
        return;

    // Initialize random number generator
    curandState state;

    curand_init(seed, i, 0, &state);

    // Generate standard normal random number
    double Z = curand_normal_double(&state);

    // Geometric Brownian Motion
    double ST = S0 * exp(
        (r - 0.5 * sigma * sigma) * T
        + sigma * sqrt(T) * Z
    );

    // European Call payoff
    double payoff = fmax(ST - K, 0.0);

    payoffs[i] = payoff;
}


// ============================================================
// CPU Monte Carlo implementation
// ============================================================
double monteCarloCPU(
    int numSimulations,
    double S0,
    double K,
    double r,
    double sigma,
    double T
) {
    double totalPayoff = 0.0;

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

        // Simple pseudo-random number
        double U = (double)rand() / RAND_MAX;

        // Avoid log(0)
        if (U <= 0.0)
            U = 1e-10;

        // Convert uniform random number to normal
        double Z = sqrt(-2.0 * log(U))
                 * cos(2.0 * M_PI * U);

        // GBM
        double ST = S0 * exp(
            (r - 0.5 * sigma * sigma) * T
            + sigma * sqrt(T) * Z
        );

        // Call payoff
        double payoff = fmax(ST - K, 0.0);

        totalPayoff += payoff;
    }

    // Discount average payoff
    return exp(-r * T) *
           (totalPayoff / numSimulations);
}


// ============================================================
// Main
// ============================================================
int main() {

    // --------------------------------------------------------
    // Option parameters
    // --------------------------------------------------------
    double S0 = 100.0;       // Initial stock price
    double K = 100.0;        // Strike price
    double r = 0.05;         // Risk-free interest rate
    double sigma = 0.20;     // Volatility
    double T = 1.0;          // Time to maturity

    int numSimulations = 1000000;

    printf("=============================================\n");
    printf(" Monte Carlo European Call Option Pricing\n");
    printf("=============================================\n\n");

    printf("Initial Stock Price : %.2f\n", S0);
    printf("Strike Price        : %.2f\n", K);
    printf("Risk-free Rate      : %.2f\n", r);
    printf("Volatility          : %.2f\n", sigma);
    printf("Time to Maturity    : %.2f\n", T);
    printf("Simulations         : %d\n\n", numSimulations);


    // ========================================================
    // CPU
    // ========================================================

    srand(1234);

    clock_t cpuStart = clock();

    double cpuPrice = monteCarloCPU(
        numSimulations,
        S0,
        K,
        r,
        sigma,
        T
    );

    clock_t cpuEnd = clock();

    double cpuTime =
        1000.0 * (double)(cpuEnd - cpuStart) / CLOCKS_PER_SEC;


    // ========================================================
    // GPU
    // ========================================================

    double *d_payoffs;

    cudaMalloc(
        (void**)&d_payoffs,
        numSimulations * sizeof(double)
    );

    int threadsPerBlock = BLOCK_SIZE;

    int blocksPerGrid =
        (numSimulations + threadsPerBlock - 1)
        / threadsPerBlock;

    cudaEvent_t start, stop;

    cudaEventCreate(&start);
    cudaEventCreate(&stop);

    cudaEventRecord(start);


    // Launch CUDA kernel
    monteCarloKernel<<<blocksPerGrid, threadsPerBlock>>>(
        d_payoffs,
        numSimulations,
        S0,
        K,
        r,
        sigma,
        T,
        1234
    );

    cudaDeviceSynchronize();


    // Allocate host memory
    double *h_payoffs =
        (double*)malloc(
            numSimulations * sizeof(double)
        );


    // Copy results GPU -> CPU
    cudaMemcpy(
        h_payoffs,
        d_payoffs,
        numSimulations * sizeof(double),
        cudaMemcpyDeviceToHost
    );


    // Calculate average payoff
    double totalPayoff = 0.0;

    for (int i = 0; i < numSimulations; i++) {
        totalPayoff += h_payoffs[i];
    }

    double gpuPrice =
        exp(-r * T) *
        (totalPayoff / numSimulations);


    cudaEventRecord(stop);
    cudaEventSynchronize(stop);

    float gpuTime;

    cudaEventElapsedTime(
        &gpuTime,
        start,
        stop
    );


    // ========================================================
    // Results
    // ========================================================

    printf("\n--------------- RESULTS ----------------\n");

    printf("CPU Option Price : %.6f\n", cpuPrice);
    printf("GPU Option Price : %.6f\n", gpuPrice);

    printf("\nCPU Time         : %.4f ms\n", cpuTime);
    printf("GPU Time         : %.4f ms\n", gpuTime);


    double speedup =
        cpuTime / gpuTime;

    printf("Speedup          : %.2fx\n", speedup);


    // ========================================================
    // Correctness verification
    // ========================================================

    double difference =
        fabs(cpuPrice - gpuPrice);

    printf("\nPrice Difference : %.6f\n", difference);

    if (difference < 1.0) {
        printf("Verification     : CORRECT\n");
    }
    else {
        printf("Verification     : DIFFERENCE DETECTED\n");
    }


    // ========================================================
    // CUDA configuration
    // ========================================================

    printf("\n----------- CUDA CONFIGURATION -----------\n");

    printf("Threads / Block  : %d\n",
           threadsPerBlock);

    printf("Blocks / Grid    : %d\n",
           blocksPerGrid);

    printf("Total Threads    : %d\n",
           blocksPerGrid * threadsPerBlock);


    // ========================================================
    // Cleanup
    // ========================================================

    free(h_payoffs);

    cudaFree(d_payoffs);

    cudaEventDestroy(start);
    cudaEventDestroy(stop);

    return 0;
}

Comments (0)

to post comments and vote
No comments yet. Be the first to share your thoughts!