C++ for Quants
  • Home
  • News
  • Contact
  • About
Author

Clement D.

Clement D.

Options Pricing Quantlib
Libraries

Develop a European Style Option Pricer with Quantlib

by Clement D. July 11, 2024

In this tutorial, we’ll walk through how to build a European style option pricer for the S&P 500 (SPX) using C++ and the QuantLib library. Although SPX tracks an American index, its standard listed options are European-style and cash-settled, making them ideal for analytical pricing models like Black-Scholes.

We’ll use historical market data to simulate a real-world scenario, define the option contract, and compute its price using QuantLib’s powerful pricing engine. Then, we’ll visualize how the option’s value changes in response to different parameters — such as volatility, strike price, time to maturity, and the risk-free rate.

1. What’s a European Style Option?

A call option is a financial contract that gives the buyer the right (but not the obligation) to buy an underlying asset at a fixed strike price on or before a specified expiration date.

The buyer pays a premium for this right. If the asset’s market price rises above the strike price, the option becomes profitable, as it allows the buyer to acquire the asset (or cash payout, in the case of SPX) for less than its current value.

In the case of SPX options, which are European-style and cash-settled, the option can only be exercised at expiration, and the buyer receives the difference in cash between the spot price and the strike price — if the option ends up in the money.

✅ Profit Scenario — Call Option Buyer

A trader buys a call option with the following terms:

ParameterValue
Strike price$105
Premium paid$5
Expiration dateSeptember 20, 2026
Break-even price$110

This call option gives the trader the right (but not the obligation) to buy the underlying stock for $105 on September 20, 2026, no matter how high the stock price goes.

📊 Profit and Loss Outcomes:

–If the stock is below $105 on expiry:
The option expires worthless.
The maximum loss is the premium paid, which is $5.

–If the stock is exactly $110 at expiry:
The option is in the money, but just enough to break even:
(110−105)−5=0

–If the stock is above $110:
The trader earns unlimited upside beyond the break-even price.

2. The Case of a SPX Call Option

Let’s now consider a realistic scenario involving an SPX call option — a European-style, cash-settled derivative contract on the S&P 500 index.

Suppose a trader considers a call option on SPX with the following characteristics:

ParameterValue
Strike price4200
Premium paid$50
Expiration dateSeptember 20, 2026
Break-even price4250

This contract gives the buyer the right to receive a cash payout equal to the difference between the SPX index value and the strike price, if the index finishes above 4200 at expiry. Because SPX options are European-style, the option can only be exercised at expiration, and the payout is settled in cash.

This option can be named with different conventions:

Depending on the context (exchange, data provider, or trading platform), the same SPX option can be referred to using various naming conventions. Here are the most common formats:

Format TypeExampleDescription
Human-readableSPX-4200C-2026-09-20Readable format: underlying, strike, call/put, expiration date
OCC Standard FormatSPX260920C04200000Used by the Options Clearing Corporation: YYMMDD + C/P + 8-digit strike
Bloomberg-styleSPX US 09/20/26 C4200 IndexUsed in terminals like Bloomberg
Yahoo Finance-styleSPX Sep 20 2026 4200 CallOften seen on retail platforms and data aggregators

All of these refer to the same contract: a European-style SPX call option with a strike price of 4200, expiring on September 20, 2026.

3. Develop a SPX US 09/20/26 C4200 European Style Option Pricer

This C++ example uses QuantLib to price a European-style SPX call option by first calculating its implied volatility from a given market price, then re-pricing the option using that implied vol.

It’s a simple, clean way to bridge real-world option data with model-based pricing.
Perfect for understanding how traders extract market expectations from prices.

#include <ql/quantlib.hpp>
#include <iostream>

using namespace QuantLib;

int main() {
    // Set today's date
    Date today(20, June, 2026);
    Settings::instance().evaluationDate() = today;

    // Option parameters
    Real strike = 4200.0;
    Date expiry(20, September, 2026);
    Real marketPrice = 150.0;   // Market price of the call
    Real spot = 4350.0;         // SPX index level
    Rate r = 0.035;             // Risk-free rate
    Volatility volGuess = 0.20; // Initial guess

    // Day count convention
    DayCounter dc = Actual365Fixed();

    // Set up handles
    Handle<Quote> spotH(boost::make_shared<SimpleQuote>(spot));
    Handle<YieldTermStructure> rH(boost::make_shared<FlatForward>(today, r, dc));
    Handle<BlackVolTermStructure> volH(boost::make_shared<BlackConstantVol>(today, TARGET(), volGuess, dc));

    // Build option
    auto payoff = boost::make_shared<PlainVanillaPayoff>(Option::Call, strike);
    auto exercise = boost::make_shared<EuropeanExercise>(expiry);
    EuropeanOption option(payoff, exercise);

    auto process = boost::make_shared<BlackScholesProcess>(spotH, rH, volH);

    // Calculate implied volatility
    Volatility impliedVol = option.impliedVolatility(marketPrice, process);
    std::cout << "Implied Volatility: " << impliedVol * 100 << "%" << std::endl;

    // Re-price using implied vol
    Handle<BlackVolTermStructure> volH_real(boost::make_shared<BlackConstantVol>(today, TARGET(), impliedVol, dc));
    auto process_real = boost::make_shared<BlackScholesProcess>(spotH, rH, volH_real);
    option.setPricingEngine(boost::make_shared<AnalyticEuropeanEngine>(process_real));

    std::cout << "Recalculated Option Price: " << option.NPV() << std::endl;
    return 0;
}

🔍 Explanation of the Steps

  1. Set market inputs: We define the option’s parameters, spot price, risk-free rate, and the option’s market price.
  2. Estimate implied volatility: QuantLib inverts the Black-Scholes formula to solve for the volatility that matches the market price.
  3. Reprice with implied vol: We plug the implied volatility back into the model to confirm the match and prepare for any further analysis (Greeks, charts, etc.).

4. Ideas of Experiments

Once your European style option pricer works for this SPX call option, you can extend it with experiments to better understand option dynamics and sensitivities:

  1. Vary the Spot Price
    Observe how the option value changes as SPX moves from 4000 to 4600. Plot a payoff curve at expiry and at time-to-expiry.
  2. Strike Sweep (Volatility Smile)
    Keep the expiry fixed and compute implied volatility across a range of strike prices (e.g., 3800 to 4600). Plot the resulting smile or skew.
  3. Volatility Sensitivity (Vega Analysis)
    Change implied volatility from 10% to 50% and plot the change in option price. This shows how much the price depends on volatility.
  4. Time to Expiry (Theta Decay)
    Fix all inputs and reduce the time to maturity in steps (e.g., 90 → 60 → 30 → 1 day). Plot how the option price decays over time.
  5. Compare Historical vs Implied Vol
    Calculate historical volatility from past SPX prices and compare it to the implied vol from market pricing. Plot both for the same strike/expiry.
  6. Greeks Across Time or Price
    Plot delta, gamma, vega as functions of SPX price or time to expiry using QuantLib’s option.delta() etc.
  7. Stress Test Scenarios
    Combine spot drops and volatility spikes to simulate market panic — useful to understand hedging behavior.

Each of these can generate powerful charts or tables to enhance your article or future dashboards. Let me know if you’d like example plots or code snippets for any of them.

July 11, 2024 0 comments
C++ libs for quants
Libraries

Best C++ Libraries for Quants: An Overview

by Clement D. June 19, 2024

C++ is widely used in quant finance for its speed and control. To build pricing engines, risk models, and simulations efficiently, quants rely on specific libraries. This article gives a quick overview of the most useful ones:

  • QuantLib – derivatives pricing and fixed income
  • Eigen – fast linear algebra
  • Boost – utilities, math, random numbers
  • NLopt – non-linear optimization

Each library is explained with use cases and code snippets: let’s discover the best C++ libraries for quants.

1. Quantlib: The Ultimate Quant Toolbox

QuantLib is an open-source C++ library for modeling, pricing, and managing financial instruments.
It was started in 2000 by Ferdinando Ametrano and later developed extensively by Luigi Ballabio, who remains one of its lead maintainers.

QuantLib is used by several major institutions and fintech firms. J.P. Morgan and Bank of America have referenced it in quant research roles and academic work. Bloomberg employs developers who have contributed to the library. OpenGamma, StatPro, and TriOptima have built tools on top of it. ING has published QuantLib-based projects on GitHub. It’s also used in academic settings like Oxford, ETH Zurich, and NYU for teaching quantitative finance. While not always publicly disclosed, QuantLib remains a quiet industry standard across banks, hedge funds, and research labs.

An example with Quantlib: Black-Scholes European call option pricing

This example calculates the fair price of a European call option using the Black-Scholes model. It sets up the option parameters, market conditions, and uses QuantLib’s analytic engine to compute the net present value (NPV) of the option.

The Black-Scholes-Merton model provides a closed-form solution for the price of a European call option (which can only be exercised at maturity).

A call option is a financial contract that gives the buyer the right, but not the obligation, to buy an underlying asset (like a stock) at a specified strike price (K) on or before a specified maturity date (T).
The buyer pays a premium for this right. If the asset price STS_TST​ at maturity is higher than the strike price, the call is “in the money” and can be exercised for profit.

Let’s implement it with Quantlib:

#include <ql/quantlib.hpp>
#include <iostream>

int main() {
    using namespace QuantLib;

    Calendar calendar = TARGET();
    Date settlementDate(19, June, 2025);
    Settings::instance().evaluationDate() = settlementDate;

    // Option parameters
    Option::Type type(Option::Call);
    Real underlying = 100;
    Real strike = 100;
    Spread dividendYield = 0.00;
    Rate riskFreeRate = 0.05;
    Volatility volatility = 0.20;
    Date maturity(19, December, 2025);
    DayCounter dayCounter = Actual365Fixed();

    // Construct the option
    ext::shared_ptr<Exercise> europeanExercise(new EuropeanExercise(maturity));
    Handle<Quote> underlyingH(ext::make_shared<SimpleQuote>(underlying));
    Handle<YieldTermStructure> flatTermStructure(
        ext::make_shared<FlatForward>(settlementDate, riskFreeRate, dayCounter));
    Handle<YieldTermStructure> flatDividendTS(
        ext::make_shared<FlatForward>(settlementDate, dividendYield, dayCounter));
    Handle<BlackVolTermStructure> flatVolTS(
        ext::make_shared<BlackConstantVol>(settlementDate, calendar, volatility, dayCounter));

    ext::shared_ptr<StrikedTypePayoff> payoff(new PlainVanillaPayoff(type, strike));
    ext::shared_ptr<BlackScholesMertonProcess> bsmProcess(
        new BlackScholesMertonProcess(underlyingH, flatDividendTS, flatTermStructure, flatVolTS));

    EuropeanOption europeanOption(payoff, europeanExercise);
    europeanOption.setPricingEngine(ext::make_shared<AnalyticEuropeanEngine>(bsmProcess));

    std::cout << "Option price: " << europeanOption.NPV() << std::endl;

    return 0;
}

Here’s how the key financial parameters map into the QuantLib code:

Option::Type type(Option::Call);  // We are pricing a European CALL
Real underlying = 100;            // Current asset price S₀ = 100
Real strike = 100;                // Strike price K = 100
Spread dividendYield = 0.00;      // Assumes zero dividend payments
Rate riskFreeRate = 0.05;         // Constant risk-free rate r = 5%
Volatility volatility = 0.20;     // Annualized volatility σ = 20%
Date maturity(19, December, 2025); // Option maturity (T ~ 0.5 years if priced in June 2025)

Supporting Structures

  • EuropeanExercise — specifies the option is European-style (only exercised at maturity).
  • PlainVanillaPayoff — defines the payoff max⁡(ST−K,0)\max(S_T – K, 0)max(ST​−K,0).
  • FlatForward and BlackConstantVol — assume constant risk-free rate and volatility.
  • BlackScholesMertonProcess — encapsulates the stochastic process assumed by the model.

Pricing Engine

Eventually, this line tells QuantLib to use the closed-form Black-Scholes solution for pricing the option.

europeanOption.setPricingEngine(
    ext::make_shared<AnalyticEuropeanEngine>(bsmProcess));

and, in the end of the code, we execute:

std::cout << "Option price: " << europeanOption.NPV() << std::endl;

.NPV() in QuantLib stands for Net Present Value.

In the context of an option or any financial instrument, NPV() returns the theoretical fair price of the instrument as calculated by the chosen pricing engine (in this case, the Black-Scholes analytic engine for a European call).

Now how to run it? First, install Quantlib. If you’re on Mac, it’s as simple as:

brew install quantlib

Now let’s compile it by adding a CMakeLists.txt:

cmake_minimum_required(VERSION 3.10)
project(QuantLibTestExample)

set(CMAKE_CXX_STANDARD 17)

find_package(PkgConfig REQUIRED)
pkg_check_modules(QUANTLIB REQUIRED QuantLib)

include_directories(${QUANTLIB_INCLUDE_DIRS})
link_directories(${QUANTLIB_LIBRARY_DIRS})

add_executable(pricer ../pricer.cpp)
target_link_libraries(pricer ${QUANTLIB_LIBRARIES})

Let’s create a build directory and run cmake:

mkdir build
cd build
cmake ..
make

And run the pricer:

➜  build ./pricer        
Option price: 6.89984

It was easy, right? Yes, Quantlib is probably among the best C++ libraries for quants. If not the best.

2. Eigen: The Quant’s Matrix Powerhouse

Eigen is a C++ template library for linear algebra, created by Benoît Jacob and first released in 2006.

Designed for speed, accuracy, and ease of use, it quickly became a favorite in scientific computing, robotics, and machine learning — and naturally found its place in quantitative finance. Eigen is header-only, highly optimized, and supports dense and sparse matrix operations, decompositions, and solvers. Its clean syntax and STL-like feel make it both readable and powerful. In quant finance, it’s especially useful for portfolio risk models, PCA, factor analysis, regression, and numerical optimization. Because it’s pure C++, Eigen integrates seamlessly into high-performance pricing engines, making it ideal for real-time and large-scale financial computations. It is one of the best C++ libraries for quants.

An example with Eigen: calculate the Value-at-Risk (VaR) of a portfolio

Value-at-Risk (VaR) estimates the potential loss in value of a portfolio over a given time period for a specified confidence level.

For a portfolio with normally distributed returns:

Let’s implement it:

#include <Eigen/Dense>
#include <iostream>
#include <cmath>

int main() {
    using namespace Eigen;

    // Portfolio weights
    Vector3d weights;
    weights << 0.5, 0.3, 0.2;

    // Covariance matrix of returns (annualized)
    Matrix3d cov;
    cov << 0.04, 0.006, 0.012,
           0.006, 0.09, 0.018,
           0.012, 0.018, 0.16;

    // Portfolio volatility (annualized)
    double variance = weights.transpose() * cov * weights;
    double sigma_p = std::sqrt(variance);

    // Convert to 1-day volatility
    double sigma_day = sigma_p / std::sqrt(252.0);

    // 95% confidence level
    double z_alpha = 1.65;
    double VaR = z_alpha * sigma_day;

    std::cout << "1-day 95% VaR: " << VaR << std::endl;

    return 0;
}

This code estimates the maximum expected portfolio loss over a single day with 95% confidence, assuming returns are normally distributed. The portfolio is composed of 3 assets with given weights and a known covariance matrix. We compute portfolio volatility using matrix operations, then scale it to daily terms and apply the standard normal quantile zαz_{\alpha}zα​.

Vector3d is equivalent to Eigen::Matrix<double, 3, 1>, representing a 3-dimensional column vector.

Matrix3d is equivalent to Eigen::Matrix<double, 3, 3>, representing a 3×3 matrix.

To run the code above, first install Eigen. I’m on Mac so:

brew install eigen

which installs the library in /usr/local/include/eigen3.

Then my CMakeLists.txt becomes:

cmake_minimum_required(VERSION 3.10)
project(eigenproject)

set(CMAKE_CXX_STANDARD 17)

include_directories(/usr/local/include/eigen3)

add_executable(var ../var.cpp)

which I use to compile:

mkdir build
cd build
cmake ..
make

And run:

➜  build ./var 
1-day 95% VaR: 0.0182592

This is a classic quant risk calculation that maps cleanly from equation to code with Eigen showing how linear algebra tools power real-world finance.

3. Boost: Statistical Foundations for Quant Models

Boost is a modular C++ library suite created in 1998 to provide high-quality, reusable code for systems programming and numerical computing. Many of its components, like smart pointers and lambdas, later shaped the C++ Standard Library. In quantitative finance, Boost is widely used for random number generation, probability distributions, statistical functions, and precise date/time manipulation. It’s not a finance-specific library, but a powerful foundation that supports core infrastructure in pricing engines and risk systems. For any quant working in C++, Boost is often running quietly behind the scenes. Boost is one of the most used and one of the best C++ libraries for quants.

An example with Boost: simulate asset price path using Geometric Brownian Motion (GBM)

Geometric Brownian Motion (GBM) is the standard model for simulating asset prices in quantitative finance. It assumes that the asset price evolves continuously, driven by both deterministic drift (expected return) and stochastic volatility (random shocks).

This is the implementation using Boost:

#include <boost/random.hpp>
#include <iostream>
#include <vector>
#include <cmath>

int main() {
    const double S0 = 100.0;   // Initial price
    const double mu = 0.05;    // Annual drift
    const double sigma = 0.2;  // Annual volatility
    const double T = 1.0;      // 1 year
    const int steps = 252;     // Daily steps
    const double dt = T / steps;

    std::vector<double> path(steps + 1);
    path[0] = S0;

    // Random number generator (normal distribution)
    boost::mt19937 rng(42); // fixed seed
    boost::normal_distribution<> nd(0.0, 1.0);
    boost::variate_generator<boost::mt19937&, boost::normal_distribution<>> norm(rng, nd);

    for (int i = 1; i <= steps; ++i) {
        double Z = norm(); // sample from N(0, 1)
        path[i] = path[i - 1] * std::exp((mu - 0.5 * sigma * sigma) * dt + sigma * std::sqrt(dt) * Z);
    }

    for (double s : path)
        std::cout << s << "\n";

    return 0;
}

This simulation produces a single daily asset path over one year, which can be visualized, stored, or used to price derivatives via Monte Carlo methods.

How to run the code above?

First, as usual, we compile it with a basic CMakeLists.txt:

cmake_minimum_required(VERSION 3.10)
project(boostgmb)
set(CMAKE_CXX_STANDARD 17)
add_executable(gbm ../gbm.cpp)

Then:

mkdir build
cd build
cmake ..
make

Then run it to get the path:

➜  build ./gbm  
100
99.2103
98.1816
97.699
96.6464
95.4814
94.584
93.0535
94.5179
94.8266
95.1813
...

The Boost.Random library handles the normal distribution sampling cleanly and efficiently, an example of plot:

4. NLopt: Non Linear Calculus For Greeks

NLopt is a powerful, open-source library for non-linear optimization, created by Steven G. Johnson at MIT. One of the best C++ libraries for quants. It supports a wide range of algorithms, from local gradient-based methods to global optimizers like COBYLA and Nelder-Mead. In quant finance, NLopt shines in model calibration, curve fitting, and computing Greeks when closed-form derivatives aren’t available. It’s especially valuable when calibrating volatility surfaces, bootstrapping curves, or minimizing pricing model errors.

An example with NLopt: calibrate delta-neutral portfolio via optimization

Delta measures how much an option’s price changes with respect to small changes in the underlying asset’s price.
For example, a delta of 0.7 means the option gains $0.70 for every $1 move in the asset.
A delta-neutral portfolio is one where the net delta is zero, meaning small price moves in the underlying don’t affect the portfolio’s value.


This is a common hedging strategy used by quants and traders to reduce directional exposure.
The goal is to balance long and short positions to make the portfolio insensitive to short-term market movements.

Let’s implement it:

#include <nlopt.hpp>
#include <vector>
#include <iostream>
#include <cmath>

// Objective: minimize absolute portfolio delta
double objective(const std::vector<double>& w, std::vector<double>& grad, void* data) {
    std::vector<double>* deltas = static_cast<std::vector<double>*>(data);
    double total_delta = 0.0;

    for (size_t i = 0; i < w.size(); ++i)
        total_delta += w[i] * (*deltas)[i];

    return total_delta * total_delta;
}

// Constraint: weights must sum to 1
double weight_constraint(const std::vector<double>& w, std::vector<double>& grad, void*) {
    double sum = 0.0;
    for (double wi : w) sum += wi;
    return sum - 1.0;
}

int main() {
    std::vector<double> deltas = { 0.7, -0.4, 0.3 };
    int n = deltas.size();

    nlopt::opt opt(nlopt::LN_COBYLA, n);
    opt.set_min_objective(objective, &deltas);
    opt.add_equality_constraint(weight_constraint, nullptr, 1e-8);
    opt.set_xtol_rel(1e-6);

    std::vector<double> w(n, 1.0 / n); // initial guess
    double minf;
    nlopt::result result = opt.optimize(w, minf);

    std::cout << "Optimized weights for delta-neutral portfolio:\n";
    for (double wi : w) std::cout << wi << " ";
    std::cout << "\nPortfolio delta: " << minf << std::endl;

    return 0;
}

The function objective computes the portfolio delta using:

total_delta += w[i] * (*deltas)[i];

and returns its absolute value.

This is what NLopt tries to minimize to reach a delta-neutral state:

The function weight_constraint enforces the condition:

return sum - 1.0;

ensuring the sum of weights equals 1 (i.e. fully invested or net flat).

In main, we set up the optimizer with:

opt.set_min_objective(objective, &deltas);
opt.add_equality_constraint(weight_constraint, nullptr, 1e-8);

NLopt uses both the objective and the constraint during optimization.

An initial guess is given as equal weights:

std::vector<double> w(n, 1.0 / n);

Finally, we run the optimization:

opt.optimize(w, minf);

and print the optimized weights and final delta.

Now how to run this code?

First, I’ve installed nlopt:

brew install nlopt

And created a CMakeLists.txt linking the library:

cmake_minimum_required(VERSION 3.10)
project(deltaneutral)

set(CMAKE_CXX_STANDARD 17)

include_directories(/usr/local/include)
link_directories(/usr/local/lib)

add_executable(deltaneutral deltaneutral.cpp)

target_link_libraries(deltaneutral nlopt)

Now, I compile:

mkdir build
cd build
cmake ..
make

and run the executable:

➜  build ./deltaneutral 
Optimized weights for delta-neutral portfolio:
0.169295 0.525312 0.305393 
Portfolio delta: 1.409e-15

This structure shows how to balance a set of option positions to make the portfolio insensitive to small moves in the underlying — a core task in quant risk management.

I hope this article on the best C++ libraries for quants for informative, stay tuned for more!

June 19, 2024 0 comments
c++ for performance
Performance

C++ for Performance: 5 Ideas to Speed Up Your Quantitative Code

by Clement D. May 16, 2024

In quantitative finance, milliseconds can mean millions. Whether you’re pricing exotic derivatives, processing high-frequency trades, or running Monte Carlo simulations, performance is non-negotiable. C++ remains the go-to language for building ultra-fast systems thanks to its low-level control and fine-tuned memory management. What are 5 tricks to optimize C++ for performance?

1. Prefer Stack Allocation Over Heap

Heap allocations (new/delete) are costly due to the overhead of dynamic memory management and potential fragmentation. Stack allocation, on the other hand, is faster, safer, and automatically cleaned up when the scope ends:

Stack vs. Heap Memory Table

ParameterStackHeap
Data type structureLinear (LIFO: Last In, First Out)Hierarchical access possible; no fixed structure
Basic allocationMemory is allocated contiguously and sequentiallyMemory can be contiguous, but is not guaranteed (depends on allocator and fragmentation)
Allocation & DeallocationAutomatic by compiler (on function entry/exit)Manual (new/delete, malloc/free) or via smart pointers
CostVery low overheadHigher overhead due to allocator logic and possible fragmentation
Limit of space sizeFixed limit per thread (set by OS, typically MBs)Limited by total available system memory
Access timeVery fast (predictable layout, cache-friendly)Slower (more indirection, potential page faults)
FlexibilityFixed-size, defined at compile timeDynamically resizable
SizeTypically smallCan grow large (useful for big data structures)
ResizeNot resizable after allocationResizable (e.g., with realloc, std::vector::resize())

So if you want speed, choose the stack allocation:

// Slower: heap allocation
MyMatrix* mat = new MyMatrix(1000, 1000); 
process(*mat);
delete mat;

// Faster: stack allocation
MyMatrix mat(1000, 1000); 
process(mat);

Use smart pointers or containers only when dynamic allocation is necessary, and favor std::array or std::vector with reserved capacity for fixed-size needs.

2. Avoid Virtual Functions in Hot Paths

A virtual function lets C++ decide at runtime which version of a function to call, based on the actual object type, not the pointer or reference type.

Virtual functions use vtables for dynamic dispatch, introducing a level of indirection that prevents inlining and hurts CPU branch prediction.

A vtable (short for virtual table) is a mechanism used by C++ to implement runtime polymorphism — specifically, virtual function calls.

When a class has at least one virtual function, the compiler generates:

  • A vtable: a table of function pointers for that class.
  • A vptr (virtual table pointer): a hidden pointer added to each object instance, pointing to the appropriate vtable.

In tight loops or latency-critical sections, replacing virtual calls with alternatives like templates or function pointers can significantly improve performance.

// Slower: virtual dispatch
struct Instrument {
    virtual double price() const = 0;
};

double sumPrices(const std::vector<Instrument*>& instruments) {
    double total = 0;
    for (const auto* instr : instruments) {
        total += instr->price(); // Virtual call
    }
    return total;
}

Using templates is way more performant:

#include <iostream>
#include <vector>

struct Bond {
    double price() const { return 100.0; }
};

template<typename T>
double sumPrices(const std::vector<T>& instruments) {
    double total = 0;
    for (const auto& instr : instruments) {
        total += instr.price();  // Resolved at compile time, can be inlined
    }
    return total;
}

3. Use reserve() for Vectors

When using std::vector, every time you push back an element beyond its current capacity, it must allocate a new memory block, copy existing elements, and deallocate the old one — which is expensive. In performance-critical paths like simulations or data loading, this overhead adds up quickly.

If you know (or can estimate) the number of elements in advance, call vector.reserve(n) to allocate memory once upfront. This avoids repeated reallocations and boosts speed significantly.

std::vector<double> prices;

// Inefficient: multiple reallocations as vector grows
for (int i = 0; i < 1'000'000; ++i) {
    prices.push_back(i * 0.01);
}

// Better: allocate memory once
std::vector<double> fast_prices;
fast_prices.reserve(1'000'000);  // Preallocate
for (int i = 0; i < 1'000'000; ++i) {
    fast_prices.push_back(i * 0.01);
}

Why Not Always Use the Stack?
The stack is fast because:

  • Allocation/deallocation is automatic.
  • It’s contiguous and cache-friendly.
  • No fragmentation or dynamic bookkeeping.

But it comes with strict limitations: the stack size is limited and it’s not resizable (fixed at compile time or needs C99-style VLAs with compiler extension).

4. Leverage Compiler Optimizations

Modern C++ compilers are incredibly powerful but you have to ask for the performance. By default, they prioritize portability and safety over speed. Turning on aggressive optimization flags like -O2, -O3, -march=native, and -flto enables advanced techniques like loop unrolling, inlining, vectorization, and dead code elimination.

These flags can deliver huge speedups especially for compute-heavy quant workloads like Monte Carlo simulations, matrix operations, or pricing curves.

# Basic optimization
g++ -O2 mycode.cpp -o myapp

# Aggressive + hardware-specific + link-time optimization
g++ -O3 -march=native -flto mycode.cpp -o myapp

🧠 Key Flags:

  • -O2: General optimizations (safe default).
  • -O3: Adds aggressive loop optimizations and inlining.
  • -march=native: Tailors code to your CPU (uses AVX, SSE, etc.).
  • -flto: Link-time optimization — lets compiler optimize across translation units.

⚠️ Use profiling tools like perf, gprof, or valgrind to validate the gains and sometimes -O3 can make things faster, but also larger or harder to debug.

5. Minimize Lock Contention

In multi-threaded quant systems, excessive use of std::mutex can serialize threads, causing performance bottlenecks. Lock contention happens when multiple threads fight to acquire the same lock, leading to context switches and degraded latency.

To reduce contention:

  • Keep critical sections short.
  • Use std::atomic for simple shared data.
  • Prefer lock-free structures or per-thread buffers where possible.

Example: Avoiding mutex with std::atomic

std::atomic<int> counter = 0;

// Thread-safe increment without a lock
void safeIncrement() {
    counter.fetch_add(1, std::memory_order_relaxed);
}


May 16, 2024 0 comments
  • 1
  • …
  • 3
  • 4
  • 5

@2025 - All Right Reserved.


Back To Top
  • Home
  • News
  • Contact
  • About