<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Namrata Priyadarshani on Medium]]></title>
        <description><![CDATA[Stories by Namrata Priyadarshani on Medium]]></description>
        <link>https://medium.com/@numpie?source=rss-2e814b231550------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*GHjPjdo0TkLGIC9zc4B4MQ.png</url>
            <title>Stories by Namrata Priyadarshani on Medium</title>
            <link>https://medium.com/@numpie?source=rss-2e814b231550------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 13:56:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@numpie/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Coin Flip that Broke Mathematics]]></title>
            <link>https://medium.com/@numpie/the-coin-flip-that-broke-mathematics-28a3c4fa0e1a?source=rss-2e814b231550------2</link>
            <guid isPermaLink="false">https://medium.com/p/28a3c4fa0e1a</guid>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[psychology]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[investing]]></category>
            <dc:creator><![CDATA[Namrata Priyadarshani]]></dc:creator>
            <pubDate>Thu, 14 May 2026 09:21:10 GMT</pubDate>
            <atom:updated>2026-05-14T09:21:10.641Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>There’s a puzzle from 1713 that accidentally discovered one of the deepest truths about market, gambling, wealth and survival. Once you understand it, you’ll know what’s wrong with most trading strategies.</blockquote><h3>The Game</h3><p>I flip a fair coin. If it lands heads, then you earn $2 and the game ends. Tails, we flip again. Heads on second flip earns you $4. Tails, flip again. Heads on third pays $8. The payout doubles each round. The game ends the first time Heads shows up.</p><p>The question is simple: <strong><em>How much should you pay to play this game?</em></strong></p><p>Let’s calculate the expected value:</p><p><strong><em>EV = (1/2) * 2 + (1/4) * 4 + (1/8) * 8 + …</em></strong></p><p>Every term equals 1. So, the sum is infinite. Which means that the math says you should pay any amount $1000, $1000000, your house, your kidney anything to play this game.</p><p>But nobody would actually do that. Most people wouldn’t even pay $15 to play this game. WHY??</p><p>This contradiction broke probability theory for almost 200 years.</p><h3>Try simulating it at your end</h3><p>If you simulate the game million times you’ll see most payouts are tiny. Median is mostly $2 or $4. Most of the times heads show up in the first or the second flip and you go home.</p><p>But the mean is wild. It can sometimes reach thousands of dollars. Why? Because once in a blue moon, tails has 20 streak. That one game pays millions. And this single game drags the average to absurdly large number.</p><p>Every run gives a different number and the mean never settles. Large samples doesn’t help here too.</p><h3>Fat-tailed World</h3><p>Most games paid tiny but a handful of games paid enormously high and those games dominated the average, no matter how big samples you took. This is the shape of a fat tail.</p><p>In a thin-tailed world like height, IQ, weight, car speed… Central Limit Theorem rescues you. You can take a handful of sample and confidently find the mean. The extremes are bounded enough that they can’t dominate.</p><p>In a fat-tailed world, rare events dominates the average. The single event can contribute more than 999999 events contribute. Here, the average is just a noisy signal.</p><p>Markets have this exact shape. A tiny number of events dominate everything.</p><p>A few trading days generate most long term market return.</p><p>A few catastrophic losses wipe out decades of volatility selling returns.<br><a href="https://medium.com/@numpie/how-i-blew-up-my-account-selling-volatility-770d8663f405">https://medium.com/@numpie/how-i-blew-up-my-account-selling-volatility-770d8663f405</a></p><p>Which mean you can’t meaningfully trust the average return of trading strategies.</p><p>In fat-tailed world average is dangerously misleading!</p><h3>SPY: Measuring in real world</h3><p>I pulled SPY’s data from 2005 onwards. This amounts to roughly 5000 trading days.</p><p>I computed basic stats and results makes SPY look beautifully behaved. Daily mean return is around 4 bips. Standard deviation is around 1.2%. If we assume a gaussian model then the prediction of a 5-sigma move would be probably once every 15000 years.</p><p>In actual data, there’s 17 days on which it happened. The largest single day drop is around -11% and largest gain is around 14.5% which are statistically impossible in gaussian distribution.</p><p>If I calculate CAGR of SPY from this data, I get 10.5% annual growth. And from the same data, I remove only the 10 best days and the CAGR drops to 6%.</p><p>These 10 out of ~5000 days accounts for around half the return in twenty years.</p><p>This is the example of fat-tailed world where the tiny number of events dominates the mean return. Backtesting with and without these 10 days makes the SPY good to invest and mediocre ETF.</p><p>What I’ve been playing with is what if I buy when SPY drops down more that 1–2%. Does it recover the next day?</p><p>The mean return I found is around 16–35 bips compared to normal 4 bips. <strong><em>This sounds like an edge.</em></strong> But as usual mean says nothing. If we look into distribution carefully, we’ll observe that the standard deviation has almost doubled. Medians next-day are less impressive than mean. It means there are a few monster reversal days which carries the entire edge. Unlucky window means edge gone.</p><p>Same lesson! <strong>In a fat-tailed world the mean does not tell you the actual distribution.</strong></p><h3>Bernoulli’s Resolution</h3><p>Ever heard people talking about lognormal distributions in market? All the time.</p><p>Daniel Bernoulli point out something very obvious in hindsight that people don’t maximize money. They maximize the utility of money. And utility is roughly logarithmic in wealth.</p><p>Going from $1000 to $2000 changes your life. But going from $1000,000 to $1001,000 doesn’t. The marginal utility of dollars decreases as you have more dollars.</p><p>Let’s redo the expected utility of coin-flip game:</p><p><strong><em>EV = (1/2) * log(2) + (1/4) * log(4) + (1/8) * log(8) + …</em></strong></p><p>The sum converges to log(4). Finite, reasonable, player pays around $4 to play the game.</p><p>Suddenly, puzzle has the answer that matches what one would pay intuitively and it also matches the median outcomes.</p><p>This is the birth of expected utility theory. It sits at the foundation of almost everything in finance.</p><h3>Why log keeps showing up</h3><p>Bernoulli’s fix looks like a hack.</p><p>Fast forward 200 years, Black-Scholes equation prices every option on every exchange in the world. It doesn’t model the stock price. It models the log of stock price.</p><p>The reason is obvious once you see it. Stocks don’t move in dollars, they move in percentage. And percentage is just log difference camouflage. Anything that compounds lives more naturally in log space.</p><p>A stock that goes up 10% one year and down 10% the next has an “average” return of zero. The actual return is <strong>-1%</strong>. The swings eat the compounding from the inside.</p><p>Even you compound in everyday life. Grow 1% everyday and you grow ~37.8 in a year. Get 1% worse everyday and you end up at ~0.03. Same arithmetic distance but wildly different places.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GeaJ2CFJrOxDjL9J.png" /></figure><h3>Constants in Chaos</h3><p><strong>One → in a fat-tailed world, “average” is a lie</strong>. When you read the fund return 20% on average, ask immidiately: dominated by how many observations? If 10 days drive half the return, the mean is the property of those 10 days and not of the strategy itself. Look at the entire distribution, the median, the tail, the worst days and know that mean can often be misleading.</p><p><strong>Two → Compounding lives in log space, not in dollar space</strong>.</p><p>Averages lie in fat-tailed worlds. Volatility eats compounding. And the strategy that quietly prints money for nine months may be the same one that goes to zero on the tenth.</p><p>The difference between getting rich and getting broke is often just one tail event you assumed would never happen.</p><p><em>Originally published at </em><a href="https://open.substack.com/pub/namratapriyadarshani/p/the-coin-flip-that-broke-mathematics?r=3ecx5w&amp;utm_campaign=post-expanded-share&amp;utm_medium=web"><em>https://namratapriyadarshani.substack.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28a3c4fa0e1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I am not imagining it]]></title>
            <link>https://medium.com/@numpie/i-am-not-imagining-it-7bc5d3ce57f1?source=rss-2e814b231550------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bc5d3ce57f1</guid>
            <category><![CDATA[psychology]]></category>
            <dc:creator><![CDATA[Namrata Priyadarshani]]></dc:creator>
            <pubDate>Fri, 08 May 2026 10:26:07 GMT</pubDate>
            <atom:updated>2026-05-08T10:26:07.698Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>I have heard unprocessed emotions stays in your body. It’s like holding a glass in your hand, it feels so light almost effortless. But hold it for a few minutes, your arms are strained. Hold it for hours, your arms goes numb. The glass didn’t get heavier. You underestimated the cost of holding it.</blockquote><p>I have held several glasses for a stretch of time and pretended my hands were free.</p><p>Here’s what was happening and I don’t want to name anyone. There was a person in my life with whom I have to communicate on a daily basis, kind of relationship from which you don’t get to walk away on a Tuesday even if you are tired. They had mood swings more frequently than a stock price reacting on every tweet. Someday, I was an old friend, smart, intelligent and it felt warm. While on other days I left conversation doubting myself, facing cold front and sarcasm implying I was less competent. I never knew which version I’d get. I was tiptoeing all the time to match energy.</p><p>I am, what psychology classifies as a Highly Sensitive Person (HSPs). I notice every tone, every sarcastic word that may sound harmless, every expression. Was it a smirk or a smile? Is the person understanding me or judging me? Was it a compliment or jealousy? Was it a genuine question or condescending rhetorical one? Has this person already formed a narrative about me? Is someone sincerely happy with my success and rooting for me or wanna pull me down? Computing all these minor things drowns me sometimes.</p><p>Most of the time the “unwelcome” advice that I get when telling these stories is that, stop overthinking everything. That why do I take everyone seriously. That people shouldn’t have that much power over me. That maybe that was not the intention of someone.</p><p>Let me briefly mention how I have processed emotions. It was through writing them down. I have an angry diary and a normal diary. I have written every swear words I thought in my mind unfiltered and I keep affirming myself. It has worked for me. It reminds me that feeling deeply is not the same thing as being weak. It gave me the courage to walk away from the situation without anybody’s validation.</p><p>I am sure there are people who can just brush off the action of others and it doesn’t bother them. They don’t overthink and “they live their life on their own terms”. I’m genuinely jealous of them. Maybe they had a childhood that taught them safety in a way mine didn’t. I am not them and I have stopped pretending that I am.</p><p>And here is what I’d offer to anyone reading this, who like me, feel things in high resolution and has been told for most of their life that it is a flaw to be fixed. Well, it isn’t. <strong>Never Silence Your Inner Voice. </strong>Listen to it, like you’d listen to a friend. That’s the way you follow your heart and your intuition. Never let anyone make you feel that you are flawed, or you are an overthinker. Trust your gut, talk to it and it will guide you home.</p><p>And the next time someone tells you that you’re overreacting, you’re too sensitive or you are imagining things… know that it’s not their place to say that. Only you know what you felt and it can’t be wrong. You are not imagining it. You never were.</p><p><em>Originally published at </em><a href="https://open.substack.com/pub/namratapriyadarshani/p/i-am-not-imagining-it?r=3ecx5w&amp;utm_campaign=post-expanded-share&amp;utm_medium=web"><em>https://namratapriyadarshani.substack.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bc5d3ce57f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I blew up my account selling volatility]]></title>
            <link>https://medium.com/@numpie/how-i-blew-up-my-account-selling-volatility-770d8663f405?source=rss-2e814b231550------2</link>
            <guid isPermaLink="false">https://medium.com/p/770d8663f405</guid>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[volatility-trading]]></category>
            <category><![CDATA[options-trading]]></category>
            <category><![CDATA[personal-finance]]></category>
            <dc:creator><![CDATA[Namrata Priyadarshani]]></dc:creator>
            <pubDate>Tue, 07 Apr 2026 07:28:12 GMT</pubDate>
            <atom:updated>2026-04-07T07:28:12.844Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>It’s a cautionary tale about notifications, margin calls and how market doesn’t care if you are on a vacation sipping virgin pina colada on a beach or chasing a sunrise you always wanted to see in life.</blockquote><p>There’s a special kind of arrogance that comes with a winning streak. You start believing that you’ve figured something out… the EDGE, the premiums will just keep rolling in.</p><p>Until they don’t!</p><p>My broker liquidated my position while I was having a “<em>me time”</em> in Bali with my phone on DND. This is the story of how I blew up my account. Not through some rogue algorithm or all-in trade but just through muted phone and margin call that nobody answered!</p><h3>Selling Volatility Felt like Easy Money</h3><p>If you’ve never sold volatility here’s the simple explanation: you collect premium by betting that market won’t move as much as implied volatility suggests. Most of the time, it doesn’t. You win small consistently! You feel like a genius.</p><p>The catch <em>and there’s always a catch</em> is that the losses, when they come, arrive all at once. I know this, everyone knows this. Still I went into the trap of collecting theta. And I said to myself… <em>I’ll keep a watch. I believe in this company. This is my limit order. This is the business I want to invest in.</em></p><p>Well guess what?</p><h3>The Most Expensive Trip of My Life</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FI_IiNAkv0ZPmR0LUBcGNQ.jpeg" /></figure><p>I had short position in the tech firms I believed in. The market was having its ups and downs but I was convinced it would recover. Worst case, I’d just hit the limit order and own a piece of a company I love. Simple, right?</p><p>I headed for my company offsite in Bali. Honestly, I have never liked Bali. Everything is a hundred hours away and the traffic is terrible and humidity… uh don’t even get me started on it! I thought I’d use the trip more as an introspective break. Trekked Mt. Batur at sunirise thinking about the next big decisions I was going to make.</p><p><strong>So, I turned off my notifications.</strong></p><h3>The Liquidation Without Witness</h3><p>In between my blissful ignorant days, market decided to move. Just a sharp, sustained grind. My margin requirements just sprinted. The broker’s system did exactly what it was designed to do, it sent warnings. Multiple warnings. And as the margin requirements were breached, my positions were liquidated.</p><p>By the time I casually checked my account the damage was done. The loss was realized and I started questioning my entire life (well that’s what I do, dramatize every instance more and more).</p><h3>Where I Went Wrong?</h3><p>At this point, with so much pain in my heart, I would say my whole life was a lie. But keeping emotions aside, here’s what I actually understood:</p><p><strong>I was the risk management.</strong> My entire risk framework depended on me.. a human being believing that I am disciplined enough. That’s not a system. That’s a single point of failure. Selling volatility isn’t bad but it’s risky and I treated it as passive income. And I disconnected myself from the one role I had.. risk management!</p><p><strong>Illusion of control :)</strong>. I felt my portfolio was fully in control. Being in control in trading is not about how things look right now but how things behave when they go wrong. In volatility selling things can go wrong very, very quickly.</p><p><strong>Systems didn’t fail me, I failed to build one.</strong> I had no stop-loss, nothing to hedge the downside, no alerts, no position sizing. <strong><em>Well rookie trader mistake all along</em></strong>. I can give an excuse that I’m new to it but yeah then shouldn’t I have done paper trading before just putting my actual money in the market.</p><h3>The Real Lesson</h3><p>If your strategy requires you to constantly watch it then your system isn’t complete. Because you won’t always be watching it.</p><p>Life happens. You travel. You sleep. You disconnect from noise. You step away from the buzz.</p><p>The traders who survive aren’t the ones who never look away. They’re the ones who built systems that don’t need them to be looking.</p><p>So what would I do differently? Reduce my exposure. Set up stop-losses… <strong>yes, even for volatility selling</strong>. Build the automated guardrails I should have had from day one. Because the market will always find the one moment your guard is down, and that’s exactly when it collects.</p><p>I learned this the expensive way :/.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=770d8663f405" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Untangling lambda and std::bind. What really happens under the hood?]]></title>
            <link>https://medium.com/@numpie/untangling-lambda-and-std-bind-what-really-happens-under-the-hood-abccba026d24?source=rss-2e814b231550------2</link>
            <guid isPermaLink="false">https://medium.com/p/abccba026d24</guid>
            <category><![CDATA[cpp-programming]]></category>
            <category><![CDATA[hft]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[low-latency]]></category>
            <dc:creator><![CDATA[Namrata Priyadarshani]]></dc:creator>
            <pubDate>Wed, 04 Mar 2026 12:41:01 GMT</pubDate>
            <atom:updated>2026-03-04T12:41:01.137Z</atom:updated>
            <content:encoded><![CDATA[<p>Every book and blog post says the same thing: “<em>Use lambdas instead of std::bind</em>”. When I started using lambdas, I didn’t question <strong>why</strong>. It looked clean, modern and for some reason very satisfying while <em>std::bind</em> looked clunky like retro C++. But the important question is, <strong>is this just a style guide or there’s something more to it inside?</strong> This post isn’t about syntax or aesthetics. It’s about under the hood <strong>code generation and optimization</strong>. Once you see what the compiler has to work with, the lambda vs bind debate stops being subjective and recommendation suddenly makes a lot of sense.</p><h3>The Setup: What Are We Actually Comparing?</h3><p>Let’s start with the simplest possible case — wrapping a function call with one bound argument:</p><pre><br>#include &lt;functional&gt;<br>#include &lt;iostream&gt;<br>#include &lt;cstdint&gt;<br><br>__attribute__ ((noinline))<br>void print_size(auto x)<br>{<br>    std::cout&lt;&lt;sizeof(x)&lt;&lt;&quot;\n&quot;;<br>}<br><br>int has_perms(int a, int b) { return a &amp; b; }<br><br>// Bind Example<br>__attribute__ ((noinline))<br>int use_bind(int x)<br>{<br>    auto b = std::bind(has_perms, 0b0110, std::placeholders::_1);<br>    print_size(b);<br>    return b(x);<br>}<br><br>// Lambda Example<br>__attribute__ ((noinline))<br>int use_lambda(int x)<br>{<br>    auto l = [](int x){return has_perms(0b0110, x);};<br>    print_size(l);<br>    return l(x);<br>}<br><br>int main() {<br><br>    volatile int x=10;<br>    use_bind(x);<br>    use_lambda(x);<br><br>}</pre><pre>16<br>1</pre><p>Wait what?! Lambda is just 1 byte!</p><p>This is because for this example lambda does not capture anything at runtime, it’s a class with just an operator(). The 1 byte is the minimum size required by C++ for any object. While bind stores function pointer and the bound arg and padding.</p><h3>What does the Assembly looks like?</h3><pre>use_bind(int):<br>        push    rbx<br>        mov     ebx, edi<br>        call    void print_size&lt;std::_Bind&lt;int (* (int, std::_Placeholder&lt;1&gt;))(int, int)&gt;&gt;(std::_Bind&lt;int (* (int, std::_Placeholder&lt;1&gt;))(int, int)&gt;) (.isra.0)<br>        mov     eax, ebx<br>        pop     rbx<br>        and     eax, 6<br>        ret<br>use_lambda(int):<br>        push    rbx<br>        mov     ebx, edi<br>        call    void print_size&lt;use_lambda(int)::&#39;lambda&#39;(int)&gt;(use_lambda(int)::&#39;lambda&#39;(int)) (.isra.0)<br>        mov     eax, ebx<br>        pop     rbx<br>        and     eax, 6<br>        ret</pre><p>Identical! Okay then the question still remains why we should prefer lambda over bind?!</p><p>Actually, modern compilers are very smart and can see through std::bind for these trivial cases. But there are scenarios where optimizer loses the battle.</p><h3>When the Difference Actually Matters</h3><h4>Case 1: Passing Through Template Functions</h4><p>Let’s see what happens when we pass different callables to a templated function.</p><pre>#include&lt;functional&gt;<br><br>// Modifying has_perms a bit<br>int has_perms(int a, int b) { return a * b + 1; }<br><br>template&lt;typename F&gt;<br>__attribute__((noinline))<br>void apply_each(std::vector&lt;int&gt;&amp; v, F func) {<br>    for (auto&amp; x : v) x = func(x);<br>}<br><br>void with_bind(std::vector&lt;int&gt;&amp; v) {<br>    apply_each(v, std::bind(has_perms, 0b0110, std::placeholders::_1));<br>}<br><br>void with_lambda(std::vector&lt;int&gt;&amp; v) {<br>    apply_each(v, [](int x) { return has_perms(0b0110, x); });<br>}</pre><p><strong>Lambda’s apply_each template instantiation</strong> — fully vectorized, no function calls:</p><pre>        ...<br>        movdqu  xmm1, XMMWORD PTR [rax]<br>        add     rax, 16<br>        movdqa  xmm0, xmm1<br>        pslld   xmm0, 1<br>        paddd   xmm0, xmm1<br>        pslld   xmm0, 1<br>        paddd   xmm0, xmm2<br>        movups  XMMWORD PTR [rax-16], xmm0<br>        cmp     rax, rdx<br>        ...</pre><p><strong>std::bind’s apply_each template instantiation</strong> — scalar loop with indirect call:</p><pre>.L15:<br>        mov     esi, DWORD PTR [rbx]<br>        mov     edi, DWORD PTR [rbp+8]<br>        add     rbx, 4<br>        call    [QWORD PTR [rbp+0]]<br>        mov     DWORD PTR [rbx-4], eax<br>        cmp     r12, rbx<br>        jne     .L15</pre><p><strong>Benchmark result:</strong></p><p>Tested sizes are 64, 1024, 16384. All tests done on <a href="http://quick-bench.com/">quick-bench.com</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vrBHYIxieOOYZRLEWFmLow.png" /></figure><h4>Case 2: Member function binding</h4><p>Let’s put our previous function in a class and see what happens.</p><pre>#include&lt;functional&gt;<br><br>struct Entity {<br>    int perms;<br>    int has_perms(int x) const { return x * perms; }<br>};<br><br>template&lt;typename F&gt;<br>__attribute__((noinline))<br>void apply_each(std::vector&lt;int&gt;&amp; v, F func) {<br>    for (auto&amp; x : v) x = func(x);<br>}<br><br>void bind_member(std::vector&lt;int&gt;&amp; v, const Entity&amp; p) {<br>    apply_each(v, std::bind(&amp;Entity::has_perms, &amp;p, std::placeholders::_1));<br>}<br><br>void lambda_member(std::vector&lt;int&gt;&amp; v, const Entity&amp; p) {<br>    apply_each(v, [&amp;p](int x) { return p.has_perms(x); });<br>}</pre><p>Lambda’s assembly:</p><pre>.L7:<br>        movdqu  xmm0, XMMWORD PTR [rax]<br>        add     rax, 16<br>        movdqa  xmm1, xmm0<br>        psrlq   xmm0, 32<br>        pmuludq xmm1, xmm2<br>        pmuludq xmm0, xmm3<br>        pshufd  xmm1, xmm1, 8<br>        pshufd  xmm0, xmm0, 8<br>        punpckldq       xmm1, xmm0<br>        movups  XMMWORD PTR [rax-16], xmm1<br>        ...</pre><p>std::bind’s assembly:</p><pre>.L26:<br>        mov     rax, QWORD PTR [rbp+0]<br>        mov     rdi, QWORD PTR [rbp+8]<br>        mov     esi, DWORD PTR [rbx]<br>        add     rdi, QWORD PTR [rbp+16]<br>        test    al, 1<br>        je      .L23<br>        mov     rdx, QWORD PTR [rdi]<br>        add     rbx, 4<br>        call    [QWORD PTR [rax-1+rdx]]<br>        ...<br>        ...<br>.L23:<br>        call    rax<br>        add     rbx, 4<br>        mov     DWORD PTR [rbx-4], eax<br>        cmp     r12, rbx<br>        jne     .L26<br>        pop     rbx<br>        ...</pre><p>The bind case looks for the virtual call of the pointer it has stored. Bind stores fat pointer even for simple classes for genericity. And once you store fat pointer, the compiler will prefer not to devirtualize which costs inlining and vectorization which we see in this example.</p><p>Let’s looks at the benchmark numbers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IIdx7JflyuM_ZBmiEAtH4w.png" /></figure><h4>Case 3: Type Erasure with std::function</h4><p>When you store a callable in std::function, type erasure hides the original type. Let&#39;s see what happens:</p><pre>#include&lt;functional&gt;<br>int has_perms(int a, int b) { return a * b; }<br><br>std::function&lt;int(int)&gt; make_bind()<br>{<br>    return std::bind(has_perms, 0b0110, std::placeholders::_1);<br>}<br><br>std::function&lt;int(int)&gt; make_lambda()<br>{<br>    return [](int x){return has_perms(0b0110, x); };<br>}<br></pre><p>Lambda’s assembly:</p><pre>make_lambda():<br>        pxor    xmm0, xmm0<br>        mov     rax, rdi<br>        movups  XMMWORD PTR [rdi], xmm0<br>        movq    xmm0, QWORD PTR .LC2[rip]<br>        movhps  xmm0, QWORD PTR .LC3[rip]<br>        movups  XMMWORD PTR [rdi+16], xmm0<br>        ret</pre><p>Bind’s assembly:</p><pre>make_bind():<br>        push    rbx<br>        pxor    xmm0, xmm0<br>        mov     rbx, rdi<br>        mov     QWORD PTR [rdi+16], 0<br>        movups  XMMWORD PTR [rdi], xmm0<br>        mov     edi, 16<br>        call    operator new(unsigned long)<br>        movq    xmm0, QWORD PTR .LC0[rip]<br>        movhps  xmm0, QWORD PTR .LC1[rip]<br>        movups  XMMWORD PTR [rbx+16], xmm0<br>        mov     QWORD PTR [rax], OFFSET FLAT:has_perms(int, int)<br>        mov     DWORD PTR [rax+8], 6<br>        mov     QWORD PTR [rbx], rax<br>        mov     rax, rbx<br>        pop     rbx<br>        ret</pre><p>Operator new is called! This would impact the performance heavily in a lot of cases. Lambda is small enough to fit in function’s small buffer optimization. Bind triggers heap allocation because of large size.</p><p>Benchmarking the above code gave the following results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dbTiBBVzcaYKWHr7Pc0T7A.png" /></figure><h3>Summarizing</h3><p>Two major factors that contribute to the loss of performance in bind are size and indirect calls of the functions. Lambda because of the simple, concrete class it creates is easy to inline whereas bind, on the other hand, has to load function pointers, get bound args from tuples and match placeholders to call arguments. These complexities kill a lot of optimizations that compiler can do.</p><p>The visibility that lambda provides to compiler is literally unbeatable.</p><blockquote>All assembly derived using flag --std=c++20 -O3 on <a href="http://godbolt.org/">godbolt.org</a> and benchmarks done on <a href="http://quick-bench.com/">quick-bench.com</a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abccba026d24" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Cost of Abstraction: std::function under the microscope]]></title>
            <link>https://medium.com/@numpie/the-cost-of-abstraction-std-function-under-the-microscope-d4b0abf8320f?source=rss-2e814b231550------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4b0abf8320f</guid>
            <dc:creator><![CDATA[Namrata Priyadarshani]]></dc:creator>
            <pubDate>Wed, 04 Mar 2026 12:31:53 GMT</pubDate>
            <atom:updated>2026-03-04T12:31:53.787Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is Type Erasure?</h3><p>In strongly typed language like C++ <strong>type</strong> is a cage. If you have a type that’s Tech you can’t assign aQuant to it. The compiler draws hard line between types even when they can do the exact same thing.</p><p>Type Erasure is a pattern where you strip away the identity and leave behind only the behavior (like “Can they code?”). It’s like putting different people into identical tags: John the Software Engineer and Jake the Quant are just Employee#1 and Employee#2.</p><h3>Is Inheritance Type Erasure?</h3><p>We all have asked this question: Isn’t virtual parent also type erasure?</p><p>When you have a base class Shape with a virtual draw() method and you pass around Shape* pointer that might point to a Circle or a Rectangle, aren’t you erasing the concrete type?</p><p>Yes! Inheritance is a form of type erasure. The concrete type is hidden behind the interface. But it’s <strong><em>intrusive</em></strong> type erasure. The types have to know about it. Circle and Rectangle must inherit from Shape . They need to opt in at the time of definition. If you are working with a third-party library that has draw method but doesn’t inherit from your Shape class, you are stuck.</p><p>True type erasures are non intrusive, and this is what we are going to talk about in this blog. The types don’t need to know they are being erased. They don’t inherit anything. They just satisfy a behaviour.</p><h3>Why do we need Type Erasure?</h3><p>The need for type erasure comes from fundamental tension in C++: the type system is rigid and compile time while the software we build often needs to be dynamic and runtime driven.</p><p>Let’s take an example of task scheduler. User submits work in form of lambdas, bound objects, functor objects or function pointers. The scheduler doesn’t need to care about type. It just need to call them.</p><p>The pattern is always: you have <em>heterogeneous</em> types, you need to store, pass or manipulate them at runtime. Anytime you are decoupling from “what something is?” to “what something can do?”, you need a type erasure.</p><h3>What C++ gives you?</h3><p>C++ has been gradually building out its type erasure toolkit. Let’s go through some of them.</p><p>void* is the oldest and the crudest form of type erasure in cpp. It erases everything. Type, behaviour, safety everything and it’s on you to cast it back safely.</p><p>std::any provided in C++17 can hold on any type. It erases the type completely but preserves just enough information to get it back via std::any_cast . It can be seen as type safe void* .</p><p>std::variant instead of erasing any types, it erases a few specific types provided by users in the template parameter. It’s a closed type erasure where you declare a set of types upfront like std::variant&lt;int,double,std::string&gt; .</p><p>std::function erases callable type specifically. It does not care if the object is lambda, functor, function pointer or bind object as long as it is callable. It owns the callable. It is the most commonly used type erasure mechanism in C++.</p><h3>std::function -&gt; Under The Hood</h3><p>We know why type erasure exists. Now, let’s build one.</p><p>Forget std::function for a moment and let’s start from the first principle. (How would Musk do it hah?)</p><p>Let’s say we want to stuff lambdas that takes an int as an argument and returns an int into a box. How do we do it? They have same behavior but for compilers they are completely unrelated types.</p><pre>template&lt;typename F&gt;<br>int invoke_erased(void* f, int arg)<br>{<br>    return (*static_cast&lt;F*&gt;(f))(arg);<br>}</pre><p>The trick is function pointers, plain old C-style function pointers.</p><p>In this example, template knows about F. But the address of invoke_erased is a plain function pointer int (*)(void*, int). No trace of Fin the pointer type.</p><p>So, invoke_erased&lt;MyLambda&gt; knows exactly what MyLambda is, it can invoke it. But the pointer to invoke_erased&lt;MyLambda&gt; is just int(*)(void*,int). The caller holding this pointer has no idea what F is. That’s the entire trick. That’s type erasure without virtual in sight.</p><p>Now let’s build simplest type erasure callable wrapper.</p><pre>// Unsafe Simple Function<br>class simple_function {<br>    void* storage = nullptr;<br>    int (*invoker)(void*, int) = nullptr;<br>    void (*destroyer)(void*) = nullptr;<br><br>  public:<br>    template&lt;typename F&gt;<br>    simple_function(F&amp;&amp; f)<br>    {<br>        storage = new F(std::move(f));<br>        invoker = [](void* addr, int arg) {<br>            return (*static_cast&lt;F*&gt;(addr))(arg);<br>        };<br><br>        destroyer = [](void* addr) {<br>            delete static_cast&lt;F*&gt;(addr);<br>        };<br>    }<br><br>    int operator()(int arg)<br>    {<br>        return invoker(storage, arg);<br>    }<br><br>    ~simple_function()<br>    {<br>        destroyer(storage);<br>    }<br>};</pre><p>The template parameter F exists only inside constructor and by the time you call operator() it’s gone like magic!</p><p>Okay now let’s take a step back and look into the performance aspects of it. Our simple_function works. It erases types, it calls and cleans up the object. But there are two costs we have quietly introduced:</p><ol><li>Heap Allocation on every construction.</li><li>An indirect call through function pointer which means loss of inlining and optimization opportunity for compiler (for example dead code elimination and vectorization).</li></ol><h3>Can we do better?</h3><p>Indirect call is fundamental cost of type erasure (We’ll see later how this can be saved sometimes). But the heap allocation? We can fix it.</p><p>Most function objects are small. Like a captured int is 4 bytes, pointers 8 bytes. So we can store small objects on stack itself. This is exactly what real implementation of std::function does. It’s called Small Buffer Optimization(SBO).</p><h3>Small Buffer Optimization</h3><p>The idea is straightforward: keep a chunk of raw bytes inside the object. If the callable fits, construct it right there. If not, fall back to heap.</p><pre>class better_function {<br>    static constexpr size_t BUF_SIZE = 8;<br><br>    alignas(max_align_t) unsigned char raw_bytes[BUF_SIZE];<br>    void* storage = nullptr;<br>    int (*invoker)(void*, int) = nullptr;<br>    void (*destroyer)(void*) = nullptr;<br><br>    public:<br>    template&lt;typename Func&gt;<br>    better_function(Func&amp;&amp; f)<br>    {<br>        using F = std::decay_t&lt;Func&gt;;<br>        constexpr bool is_heap = (sizeof(F) &lt;= BUF_SIZE) ? false : true;<br>        if constexpr(!is_heap)<br>            storage = new ((void*)raw_bytes) F(std::move(f));<br>        else<br>            storage = new F(std::move(f));<br><br>        invoker = [](void* addr, int arg){<br>            return (*static_cast&lt;F*&gt;(addr))(arg);<br>        };<br><br>        destroyer = [](void* addr){<br>            if constexpr(is_heap)<br>                delete static_cast&lt;F*&gt;(addr);<br>            else<br>                static_cast&lt;F*&gt;(addr)-&gt;~F();<br>        };<br>    }<br><br>    int operator ()(int arg)<br>    {<br>        return invoker(storage, arg);<br>    }<br><br>    ~better_function()<br>    {<br>        destroyer(storage);<br>    }<br>};</pre><p>The if constexpr resolves at compile time. For small lambdas, callable lives directly inside better_function. This is also implemented in standard std::function in libstdc++. You can see the boundary of SBO yourself in standard lib, override the global operator new in your executable.</p><pre>void* operator new(size_t n)<br>{<br>    std::cout&lt;&lt;&quot;Malloc called for size: &quot;&lt;&lt; n &lt;&lt;&quot;\n&quot;;<br>    return std::malloc(n);<br>}</pre><pre>// Play with ARR_SIZE to get different outputs<br>int main() {<br>    constexpr size_t ARR_SIZE = 5;<br>    std::function&lt;int(int)&gt; f1 = <br>    [arr = std::array&lt;int, ARR_SIZE&gt;{}](int i){<br>                  return arr[i];<br>    };<br>}</pre><h3>What you store matters: Lambda vs Bind</h3><p>SBO only helps if the choice of your callable fits in the buffer. And this is where your choice of callable matters more than you think.</p><p>A captureless lambda is 1 byte (minimum required byte for objects). But bind stores function pointers (8 bytes) and every argument that you provide adds additional bytes to it along with padding.</p><p>Let’s take this simple example:</p><pre>int has_perms(int a, int b) { return a &amp; b; }<br>int main() {<br><br>    // Lambda vs bind<br>    auto b = std::bind(has_perms, 0b0110, std::placeholders::_1);<br>    auto l = [](int x) { return has_perms(0b0110, x); };<br><br>    std::cout &lt;&lt; sizeof(b) &lt;&lt; &quot;\n&quot;; // 16<br>    std::cout &lt;&lt; sizeof(l) &lt;&lt; &quot;\n&quot;; // 1<br><br>    better_function f_bind(b); // Malloc called for size: 16<br>    better_function f_lambda(l);<br>}</pre><p>For same operation bind triggers heap allocation here. Same behavior, different cost, just because of how the callable is represented.</p><p>But size is only half the story. The other half is what the compiler can see and this depends on how you use the callable.</p><h3>The Inlining Gap</h3><p>When you pass a lambda to a template function (not as std::function), the compiler sees a concrete type with a visible operator(). It can inline the body and once it inlines, optimizations like dead code elimination, constant folding and especially <strong>vectorization</strong> follows.</p><p>When you pass a std::bind expression to the same template function, the compiler sees a wrapper that stores function pointer internally. This hinders the optimization that dramatically shows difference in latency.</p><p>Let’s take this loop:</p><pre>template&lt;typename F&gt;<br>void apply_each(std::vector&lt;int&gt;&amp; v, F func) {<br>    for (auto&amp; x : v) x = func(x);<br>}</pre><p>If we look at the assembly, we’ll see that the version with lambda is vectorized while with std::bind is calling a function. (I wrote a detailed breakdown of this with full assembly analysis here <a href="https://medium.com/@numpie/abccba026d24">https://medium.com/@numpie/abccba026d24</a> )</p><p>But what if you pass through std::function instead of template function?</p><pre>// std::function parameter: type is erased<br>void apply_func(std::vector&lt;int&gt;&amp; v, std::function&lt;int(int)&gt; func) {<br>    for (auto&amp; x : v) x = func(x);<br>}</pre><p>Now std::function has erased the type. Loop compiles to same indirect call for both lambda and std::bind.</p><pre>.L27:<br>        mov     eax, DWORD PTR [rbx]<br>        mov     DWORD PTR [rsp+12], eax<br>        cmp     QWORD PTR [rbp+16], 0<br>        je      .L29<br>        lea     rsi, [rsp+12]<br>        mov     rdi, rbp<br>        add     rbx, 4<br>        call    [QWORD PTR [rbp+24]]<br>        mov     DWORD PTR [rbx-4], eax<br>        cmp     r12, rbx<br>        jne     .L27</pre><p>No vectorization for either. No inlining for either. The body of lambda and std::bind still differs but this is the cost you pay when you use std::function.</p><h3>What we’ve learned</h3><p>We started by asking a simple question: What happens when we call std::function.</p><p>Now we know it’s simply composed of function pointers and a storage pointer and uses the oldest trick in C (casting the pointer to void* and back).</p><p>The costs are clear: indirect calls (hindering optimizations) and heap allocation when your allocation exceeds SBO size.</p><p>We also saw what you put inside std::function matters: a captureless lambda is 1 byte fits the SBO, while std::bind doing the same job is 16 bytes and can spill to the heap.</p><p>If you can keep callables as template parameter, do that! Reach for std::function when you genuinely need type erasure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d4b0abf8320f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Carry Currency Trades: How traders borrow cheap, invest high and sometimes get burned]]></title>
            <link>https://medium.com/@numpie/carry-currency-trades-how-traders-borrow-cheap-invest-high-and-sometimes-get-burned-908d7bf69fde?source=rss-2e814b231550------2</link>
            <guid isPermaLink="false">https://medium.com/p/908d7bf69fde</guid>
            <category><![CDATA[forex-trading]]></category>
            <category><![CDATA[hft]]></category>
            <category><![CDATA[algorithmic-trading]]></category>
            <category><![CDATA[hedge-funds]]></category>
            <category><![CDATA[trading]]></category>
            <dc:creator><![CDATA[Namrata Priyadarshani]]></dc:creator>
            <pubDate>Mon, 19 Jan 2026 14:06:06 GMT</pubDate>
            <atom:updated>2026-01-22T18:35:20.302Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>A simple idea: Borrow money where interest rates are low and invest where interest rates are high. Doesn’t this sound like free money?</blockquote><p>In August 2024, global markets experienced one of the most dramatic sell-offs. Japan’s Nikkei 225 went down by 12.4% in a single day, S&amp;P 500 went down 3% and crypto by 20%. The culprit? <strong>Yen Carry Trade</strong> strategies began to unwind.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_v25UHsf6linPVnQW5dyZw.png" /></figure><h3>What is a Carry Currency Trade?</h3><p>A Carry Currency Trade is a trading strategy where you borrow money in a currency with low interest rates and invest that money in assets denominated in currency with higher interest rates. The goal is to profit from the interest rate differential, the <strong>carry</strong>, between the two currencies.</p><p>Here’s an example to understand intuitively:</p><ol><li><strong>Borrow in Japan</strong> at nearly zero interest rate.</li><li><strong>Convert to USD</strong>.</li><li><strong>Invest in US</strong> risk free assets like T-bills.</li><li><strong>Collect the spread</strong> on interest rate differential.</li><li><strong>Repay the loan</strong>. Keep the spread profit.</li></ol><h3>Why some countries maintain high interest rates?</h3><p>Let’s compare Japan and Australia to understand this.</p><p>Interest rates are increased by countries to fight inflation. Basics of all rates are:<br><strong><em>inflation rises -&gt; raise rates<br>growth weakens -&gt; cut rates</em></strong></p><p>Now, Australia is a commodity exporter. It’s economy is heavily driven by commodities, especially iron, coal, natural gas, gold and lithium. These commodities are priced in international markets. Which means Australia’s income depends on global commodity prices. And that’s why, Australian currency is called <strong>commodity currency</strong>.</p><p>When commodity prices rise, export revenues surge. Foreign money flows into Australia creating strong economic momentum. Booms are sudden and volatile if compared to other developed countries where growth comes from services and are slow and stable. To control this inflation risk, Australia often responds by raising interest rates aggresively.</p><p>So, long story short, the cyclical booms in Australia can cause inflation. On the flip side, Japan faces deflation risk. It has aging population, taking fewer risk, spending less and saving more. This weak demand leads to slower growth of companies, flattened wages and prices. The reality that prices will stay flat or fall discourage spendings more and that creates a feedback loop for deflation. Japan responds to this situation by encouraging investments by keeping interest rates low (sometimes even negative).</p><h3>August 2024 Crash</h3><p>For years, conditions were perfect for Yen Carry Trades. Japan’s ultra low interest rates and depreciation of Yen made traders more profitable using this strategy. But in mid 2024, the Bank of Japan surprised the market by increasing the interest rates. Traders rushed to close their positions, selling assets to buy back yen. This strengthened yen forcing more traders to liquidate their positions due to margin calls. And this cycle accelerated.</p><p>Although, the recovery was remarkable in the market which leads me to think whether carry trades unwind is violent but only short-lived?</p><h3>Popular Carry Trades Pair</h3><p><strong>Developed Market Pairs:</strong></p><ol><li>USD/JPY: Japan’s decades on zero interest rates made yen the funding currency.</li><li>NZD/JPY and AUD/JPY: Australia and New Zealand maintains higher interest rates compared to other developed countries which made them popular for carry currency trades.</li><li>CHF(Swiss Franc): Switzerland has also maintained ultra low IRs making it another funding currency.</li></ol><p><strong>Emerging Market Pairs:</strong></p><ol><li>USD/BZL and USD/MXN: Brazil and Mexico have aggresively increased their IRs creating attractive spreads and delivering higher returns.</li><li>USD/TRY: Turkey offers extremely high yields but comes with substantial currency volatility and political risk.</li></ol><h3>What are the risks involved?</h3><ol><li><strong>Currency Risk: </strong>Exchange rate movement is one of the biggest risk factor. If it moves in your direction, well good but if not it might wipe out your capital. On top of that, leverage aplifies losses too, just as it amplifies profits.</li><li><strong>Stairs up, slide down: </strong>Carry trades have slow and steady profits over months or years. But losses are violent over days and weeks.</li><li><strong>Central Banks are unpredictable: </strong>Any unexpected policy can reverse months of careful positioning.</li><li><strong>Crowding Problem: </strong>When trades become too popular, it becomes dangerous. When everyone holds the same position, liquidity disappears when you need it the most.</li></ol><h3>How trading firms play this?</h3><ol><li><strong>Hedging with Options: </strong>Traders use RiskReversals. Buying put option for high interest rate currency as an insurance and selling call option to finance the put option. This caps the profit but also prevents catastrophic loss.</li><li><strong>Arbitrage: </strong>If there’s pure arbitrage opportunity where using forward contract to lock in exchange rates is available, that eliminates currency risk entirely.</li><li><strong>Leverage Discipline: </strong>Keeping a leverage ratio that gives you room to survive in volatility is far better than a higher leverage ratio that wipes you out on a bad week.</li></ol><h3>In a Nutshell</h3><p>Carry trades are not free money. They are the bet that interest rate differentials will persist, funding currency won’t appreciate, market will provide liquidity when you need it. When these conditions hold, carry trades print money. Strategy has worked historically and the same strategy has shown popular crashes. But the real question isn’t whether the strategy will work. The question is can you survive the drawdowns?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=908d7bf69fde" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing Life’s Hot Path]]></title>
            <link>https://medium.com/@numpie/designing-lifes-hot-paths-208dbd29ea35?source=rss-2e814b231550------2</link>
            <guid isPermaLink="false">https://medium.com/p/208dbd29ea35</guid>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[life]]></category>
            <category><![CDATA[hft]]></category>
            <category><![CDATA[low-latency]]></category>
            <dc:creator><![CDATA[Namrata Priyadarshani]]></dc:creator>
            <pubDate>Tue, 06 Jan 2026 20:53:28 GMT</pubDate>
            <atom:updated>2026-01-06T21:07:12.057Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*ep1U4f6FFHz1DO6Y7tevBw.jpeg" /></figure><blockquote>In <strong>High-Frequency Trading (HFT)</strong>, the hot path refers to the critical, time-sensitive code path that processes market data and executes orders. This is where nanoseconds matter. But the hot path exists beyond trading colocations and sillicon chips. It exists in our life. We just never bothered to run a Profile Guided Optimization (PGO) on it.</blockquote><p>Every poet compares their lover to the moon or hummingbirds. I borrow my metaphors from HFT. I believe that just as we optimize HFT systems, we can optimize life too. Shaving off the few nanos that put us ahead and give amazing returns can be applied in real life too. And just as we lie on grass at midnight, staring at the moon, questioning the meaning of HFT, we question the meaning of life too. And just as we know how important HFT is for liquidity, we can come up with a made-up, trumped-up meaning of life too.</p><h3><strong>What is life’s hot path?</strong></h3><p>In life the hot path isn’t grand cinematic moments, they execute rarely. The actual hot path is the set of decisions running on autopilot. When we wake up? What we eat? Which tasks we pick up first? Which notifications get attention, in what order? How you respond when someone irritates you? What you do in the low energy afternoon hours? What’s your default behavior when you’re bored?</p><p>These decisions feel insignificant in isolation. Any single instance barely matters but that’s what makes them dangerous. They compound silently. A small inefficiency in code that runs twice a year won’t matter but the same in the code that runs every millisecond will bankrupt you.</p><h3><strong>Profile before you optimize</strong></h3><p>In HFT, tuning code based on hunch mostly leads to more entropy. You don’t guess where latency hides, you check performance metrics.</p><p>Test your life in the same way. You’ll find the results uncomfortable. The hours don’t vanish in big decisions or meaningful work. They leak out in doom scrolling, context switching and in dead time between intentions and actions. Most people optimize with gut feeling.But when you profile your day, you’ll discover the bottlenecks are embarrassingly mundane.</p><h3>Precompute what you can</h3><p>Every unnecessary computation in critical path adds delay. The fastest system finds the scope to precompute stuff.</p><p>In life latency hides behind our decision fatigue. The mundane kind: standing before your closet every morning recomputing what to wear, opening your phone to rethink what to eat, letting each notification interrupt for fresh evaluation.</p><p>But the expensive recomputations run deeper. Figuring out how you work under pressure. Discovering what feedback helps versus what just stings. Understanding which friendships survive difficulty.</p><p>The solution is to evaluate once, journal it and use the result.</p><p>For daily decisions just standardize meals, fix your wardrobe, batch notifications. For deeper knowledge when you learn something about yourself, encode it as a decision. “I don’t work well after 4pm” becomes a schedule constraint, “Condescending tone drains me” becomes a filter. They are not the feelings you need to rediscover. You’ve already solved most of your recurring problems at least once. Trust the results and use them.</p><h3>Cache Important Data</h3><p>Your brain has cache hierarchies too. L1 is what you are actively holding in mind. L2 is what you can recall. L3 probably you’ve offloaded somewhere.</p><p>Issue is we treat L1 like it’s infinite. We try to hold everything here. Grocery list, unresolved arguments, shopping list for vacation, deadlines, your friends breakup story. And this leads to the eviction of important things from L1.</p><p>Solution is to demote what you don’t need and prefetch the ones you do.</p><p>Write things down to offload them from your L1 cache. You are demoting it to lower level, freeing L1 for what actually matters. Read your notes to prefetch. Have a morning reminder to follow your routine or before a hard conversation, load what you wrote after the last one.</p><p>This is what journaling is: you write it to evict data and read it to prefetch… Managing the cache smoothly and optimizing your hot path.</p><h3>Avoid False Sharing</h3><p>In multithreaded setups false sharing kills performance silently. Two processors work on independent data, but because that data sits on the same cache line, they constantly invalidate each other because of architectural interference.</p><p>In real life, relationships have false sharing. You and your partner have independent goals but you share a life. Your need for vacation collides with their work pressure. Your energy dips and they become a chatterbox. Neither is wrong, just beaten up by false sharing.</p><p>The fix is to add padding. Give each processor its own cache line, even if it wastes memory. Separate workspaces, independent routines, reserved me-time eliminates false sharing and makes the real sharing amazing!</p><h3>Spend on Colocation</h3><p>HFTs pay millions to colocate servers next to exchange matching engines. Physical proximity matters. We colocate in life too. Living in the same city as our industry’s hub. Going to office to be in the same room as the decision makers.</p><p>Your environment shapes you. The random encounter, the overheard conversation, the introduction that happens because you were physically present. That’s why people pay absurd rents to live in certain cities. It has long term returns compounded even if the cost looks unreasonable in the moment.</p><h3>Questioning Meaning</h3><p>I gave it a thought and I feel the metaphor breaks here.</p><p>We know why we are optimizing in HFT, it will make money. Straightforward feedback: faster fills, better PnL.</p><p>But life has no matching engine, no EOD reports confirming optimizations worked. You can profile your days, precompute your decisions, manage your cache perfectly and still not know what was it all for?</p><p>Maybe the meaning is emergent. Maybe it comes slowly, in designing the system itself. The satisfaction of a well designed routine? A life that runs a little smoother than it did last year. The ability to observe yourself and choose to improve?</p><p>We keep asking, we keep looking and somewhere between asking the meaning and optimizing, we build life. A bewildering and still stunning life!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=208dbd29ea35" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>