Site Tools


cuda-q-performance

Performance Optimization

Performance optimization for quantum kernels involves minimizing gate count, leveraging GPU acceleration, and efficient batching.

#include "cudaq.h"
#include <chrono>
#include <vector>
 
// Naive kernel: many redundant operations
struct NaiveKernel {
  void operator()(int n) __qpu__ {
    cudaq::qvector q(n);
 
    // Redundant: h then x then h = not much
    for (int i = 0; i < n; i++) {
      h(q[i]);
      x(q[i]);
      h(q[i]);
    }
 
    mz(q);
  }
};
 
// Optimized kernel: simplified gates
struct OptimizedKernel {
  void operator()(int n) __qpu__ {
    cudaq::qvector q(n);
 
    // Simplified: h-x-h ≈ z (up to global phase)
    for (int i = 0; i < n; i++) {
      rz(M_PI, q[i]);  // Z gate (cheaper than h-x-h)
    }
 
    mz(q);
  }
};
 
int main() {
  // Benchmark naive vs optimized
  int n = 20;
  int shots = 10000;
 
  cudaq::set_target("nvidia");  // Use GPU for speed
 
  // Time naive kernel
  auto start = std::chrono::high_resolution_clock::now();
  auto naive_result = cudaq::sample<NaiveKernel>(shots, n);
  auto end = std::chrono::high_resolution_clock::now();
  auto naive_time = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
  printf("Naive kernel: %lld ms\n", naive_time);
 
  // Time optimized kernel
  start = std::chrono::high_resolution_clock::now();
  auto opt_result = cudaq::sample<OptimizedKernel>(shots, n);
  end = std::chrono::high_resolution_clock::now();
  auto opt_time = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
  printf("Optimized kernel: %lld ms\n", opt_time);
 
  printf("Speedup: %.2fx\n", double(naive_time) / opt_time);
 
  return 0;
}

Optimization Tips

  1. Minimize gate count: fewer gates = faster execution + less error
  2. Use GPU: 100x faster than CPU for large circuits
  3. Batch shots: collect many samples per kernel call
  4. Avoid deep circuits: exponential slowdown with depth

Performance depends on backend and hardware. Profile early and often.

cuda-q-performance.md · Last modified: by 127.0.0.1