<?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 Karthick T. Sharma on Medium]]></title>
        <description><![CDATA[Stories by Karthick T. Sharma on Medium]]></description>
        <link>https://medium.com/@mrintrovert?source=rss-a1513e49f9a4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*d7NhpXr7KE0I5a0sreJfkA.jpeg</url>
            <title>Stories by Karthick T. Sharma on Medium</title>
            <link>https://medium.com/@mrintrovert?source=rss-a1513e49f9a4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 21:54:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mrintrovert/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[Same number, different emergency: why children aren’t small adults]]></title>
            <link>https://medium.com/@mrintrovert/same-number-different-emergency-why-children-arent-small-adultsa-heart-rate-of-150-beats-per-ba48bcc5f493?source=rss-a1513e49f9a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba48bcc5f493</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[pediatrics]]></category>
            <dc:creator><![CDATA[Karthick T. Sharma]]></dc:creator>
            <pubDate>Thu, 19 Nov 2026 04:52:43 GMT</pubDate>
            <atom:updated>2026-11-19T05:13:51.417Z</atom:updated>
            <content:encoded><![CDATA[<p>A heart rate of 150 beats per minute.</p><p>If it belongs to a one-month-old baby, it’s an ordinary Tuesday. A <a href="https://pmc.ncbi.nlm.nih.gov/articles/PMC3789232/">large review of healthy children</a> puts the typical heart rate at that age at about 145.</p><p>If it belongs to a 40-year-old sitting on the sofa, it’s a different story. The usual adult resting range is 60 to 100, and <a href="https://www.mayoclinic.org/healthy-lifestyle/fitness/expert-answers/heart-rate/faq-20057979">Mayo Clinic</a> suggests talking to a health professional if yours is regularly above 100.</p><p>Same number. Two completely different meanings.</p><p>Now picture that 150 landing in your model. What does the model do with it? (By “model” I mean any software that reads patient data and decides what looks wrong.)</p><h3>Whose foot is it?</h3><p>Walk into a shoe shop and ask for a size 5. Before anyone fetches a box, you’ll get a question back: who’s it for?</p><p>That’s because “size 5” is two different shoes. There’s a toddler’s size 5 and an adult’s size 5, and one would fit inside the other with room to spare.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AlE5_IBgMGXqc0GL.png" /><figcaption><em>The same label on two shoes. “Size 5” only means something once you know whose foot it is.</em></figcaption></figure><p>Clinical numbers work the same way. A heart rate, a blood test result and a drug dose are all labels on a box. You can’t read any of them until you know whose foot they belong to.</p><p>That’s the idea of this whole post in one line: <strong>a number needs an owner.</strong> Doctors who look after children have an older, shorter version: children aren’t small adults.</p><p>Hold on to the shoes. They’ll come back for blood tests, and again for medicines.</p><h3>Normal moves as children grow</h3><p>A child’s “normal” shifts a lot, and fast.</p><p>The <a href="https://pmc.ncbi.nlm.nih.gov/articles/PMC3789232/">review from the opening</a> pooled heart-rate data on about 143,000 healthy children and charted the normal range from birth to 18. Around one month old, the median (middle) heart rate is about 145 beats a minute. By 15 to 18, it’s about 73.</p><p>So 150 sits comfortably inside a young baby’s normal range, and far above the top of a teenager’s.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*PuiGuWuUKwOInPAn.png" /><figcaption><em>Median heart rate and its normal range by age band, from the 2011 Lancet review, against the adult resting range from </em><a href="https://www.mayoclinic.org/healthy-lifestyle/fitness/expert-answers/heart-rate/faq-20057979"><em>Mayo Clinic</em></a><em>. The 150 is a hypothetical reading.</em></figcaption></figure><p>The part I find most interesting is that <strong>even the guideline age bands were off.</strong> In fairness, those bands were written for resuscitation and triage, and the review’s authors thought many were probably set by clinical consensus rather than measured on healthy children.</p><p>Still, when the team checked the normal ranges printed in clinical guidelines against their data, they found “marked disagreement”. Many limits were too loose. Some were so tight that, at some ages, more than half of healthy children would have counted as abnormal.</p><p>One life-support guideline at the time put the top of normal for ages 2 to 10 at 140. For most of that age span, that’s above the top of the real normal range.</p><p>If you build models, this should feel familiar. A guideline table is a model of “normal” too. This review was, in effect, a big validation set: fresh data the table had never been tested on.</p><h3>The “abnormal” blood test that just means growing</h3><p>A healthy teenage boy can have a blood test result almost four times a man’s upper limit, and be perfectly fine.</p><p>The test is ALP, short for alkaline phosphatase. It’s an enzyme, a protein that speeds up chemical reactions, found in many tissues but especially the liver and bones. Doctors use it to check on both (<a href="https://medlineplus.gov/lab-tests/alkaline-phosphatase/">MedlinePlus</a>). Growing bone makes a lot of it, so ALP runs highest in childhood and puberty (<a href="https://www.ncbi.nlm.nih.gov/books/NBK459201/">StatPearls</a>).</p><p>A <a href="https://doi.org/10.1373/clinchem.2015.240515">2015 Canadian study</a> measured ALP in about 12,000 people aged 3 to 79, on the same lab machine for every age, so differences between machines aren’t muddying the comparison. The top of the healthy range was 438 units per litre for boys aged 11 to 15, and 116 for men.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-t3U7J_Ilsmvlduo.jpg" /></figure><p>Run his result through a rule built on adult ranges and it looks like his liver is in trouble. It isn’t. His bones are growing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Vf31oOzqsWe9qi7g.png" /><figcaption><em>Healthy reference ranges for ALP by age and sex, from the </em><a href="https://doi.org/10.1373/clinchem.2015.240515"><em>2015 Canadian study</em></a><em>. A teenage boy’s upper limit is almost 4 times a man’s.</em></figcaption></figure><p>So when a model sees an ALP of 300, ask the shoe-shop question first: whose foot?</p><h3>Smaller isn’t the same as younger</h3><p>A wrong normal range gives you false alarms and missed problems. With medicines, getting the owner wrong can do direct harm.</p><p><a href="https://doi.org/10.1001/archpedi.1959.02070010763001">In 1959, doctors reported</a> that babies given large amounts of the antibiotic chloramphenicol were collapsing as their circulation failed, and some died. <a href="https://doi.org/10.1056/NEJM195912242612604">A study of premature babies that year</a> found more deaths among those given the drug. The condition became known as grey baby syndrome, and <a href="https://doi.org/10.3389/fped.2025.1733059">one of its signs</a> is ashen-grey skin.</p><p>The problem wasn’t just that the babies were small. A newborn’s liver <a href="https://doi.org/10.3389/fped.2025.1733059">can’t yet do much of the chemical work</a> that lets the body get rid of this drug, and <a href="https://doi.org/10.1056/NEJM196004212621601">newborn kidneys clear it more slowly too</a>. So each dose landed on top of what was left of the last one, and the drug built up to toxic levels.</p><p>Today, children’s doses are commonly worked out per kilogram of body weight. That handles size, but not maturity: a <a href="https://doi.org/10.3390/ph19071090">2026 review</a> warns that simply scaling adult doses by weight misses how a baby’s drug-processing enzymes and organs mature.</p><p>You can’t cut an adult shoe down to fit a toddler, and you can’t simply scale down an adult dose either. If your model sees doses, it needs the child’s weight and age right next to them.</p><h3>Where adult rules meet children</h3><p>Clinicians already handle this on paper. Children’s early-warning scores, the bedside checklists that flag a child who is getting worse, work in age bands, though <a href="https://pmc.ncbi.nlm.nih.gov/articles/PMC3789232/">some widely used ones refer to the same guideline ranges</a> the review found were off. A model has to be told, or has to see enough children to learn it.</p><p>The trouble starts where adult rules and models meet children without that context: an emergency department that sees every age, or a model trained mostly on adults. That’s where the 150 lands.</p><p>Take an adult-style rule: alert if heart rate is above 100. Until about age 4, the median heart rate is above 100, so it would ring for plenty of healthy children (see the chart above). It also misses the opposite case. By the adult range of 60 to 100, a two-month-old at 70 looks calm. In fact, 70 is far below the lowest normal for that age (about 107), which makes it a red flag.</p><p>Now give the rule the patient’s age: alert only above the top of the normal range for that age (roughly the 99th centile: the value only about 1 in 100 healthy children that age go above).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rrhw6G81eVEcXm9S.png" /><figcaption><em>Five made-up patients, two rules. The age-aware rule uses each age band’s top of normal from the 2011 review’s appendix. Once the rule knows the age, three of the five alerts go away.</em></figcaption></figure><p>That helps, but it doesn’t finish the job. It will still flag some healthy children, so you’d measure its alert rate in the place it’s going to run. And age is only one thing that moves a heart rate: fever and anxiety can push it up too.</p><p>In a <a href="https://doi.org/10.1542/peds.2012-2443">2013 study of children in hospital</a>, up to 54% of heart-rate readings fell outside textbook normal ranges. Alarm on all of those and you get alarm fatigue: so many alerts that people stop hearing them.</p><p>A monitor takes a lot of readings, so even a small false-alarm rate adds up fast. For borderline readings, better rules look at whether the reading persists, which way it’s trending and what the other signs say, while a truly dangerous value still raises the alarm straight away.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*isjAhXg8ofnga12UzcKy8w.jpeg" /></figure><p>For a model, there are two fixes worth trying:</p><ol><li><strong>Give the model the owner.</strong> Feed in age, plus weight and sex where they matter, next to each value. Then it can learn that 150 means different things at different ages.</li><li><strong>Translate the number before the model sees it.</strong> Compare each value with healthy children of the same age, and pass on how unusual it is. Not “150”, but “near the middle for a one-month-old”.</li></ol><p>The second is how clinicians already read growth: a child’s height against other children the same age.</p><p>Age is the clearest missing context, but not the only one: weight, sex and <a href="https://doi.org/10.3390/ph19071090">how early a baby was born</a> matter too. A number in a health record rarely carries all the context it needs.</p><h3>For the engineers: giving the model the owner</h3><p><em>Skippable. If you don’t build models, jump to the takeaway.</em></p><h3>Three options</h3><p>(1) and (2) are the story’s two fixes; (3) is the tempting one.</p><p><strong>(1) Age as a feature.</strong> Easiest: pass age in and hope the model learns the interactions (“150 is ordinary at one month, alarming at 40”). Trees and neural networks can, if every age is well covered; a linear model can’t without interaction terms. If children are a thin slice of your data, that’s a lot to ask.</p><p><strong>(2) Normalise for age first.</strong> Turn each raw value into a z-score or centile (percentile) against healthy children of the same age and sex. You borrow knowledge from a large healthy reference instead of asking the model to rediscover it from your smaller, sicker cohort. The catches: you inherit the reference’s assumptions, and lose the number’s absolute size. Keep the raw value as a feature too, and clip extreme scores.</p><p><strong>(3) One model per age band.</strong> Neat on a whiteboard. In practice each band gets less data, you inherit cliffs at the band edges, and you maintain several models.</p><p>With small data, (2) plus age and the raw value is a sensible first try.</p><h3>Bins have cliffs; curves don’t</h3><p>The heart-rate review drew smooth centile curves using kernel regression, a smoothing method. Bins create cliffs: a baby who is 364 days old and one who is 366 days old get different “normals”, although their hearts have never heard of birthdays.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1ld6ya8m7zQGiVAd.png" /><figcaption><em>Age bins put a cliff at every edge, so two babies two days apart get different “normals”; a smooth curve doesn’t. The shape is illustrative, not real reference data.</em></figcaption></figure><p>Published tables are still banded, even over smooth curves. The review’s appendix lists cut-offs per age band, which is why our heart-rate chart and five-patient figure use bands too.</p><p>Lab bins also differ by test: <a href="https://pmc.ncbi.nlm.nih.gov/articles/PMC5387699/">CALIPER needed seven age groups for ALP but only three for ALT</a>. Don’t copy one test’s bins onto another.</p><h3>From a reference table to a score</h3><pre>import numpy as np<br><br># ILLUSTRATIVE NUMBERS ONLY. These are NOT clinical reference values.<br># Replace them with a published reference built from healthy children<br># (in real life: one table per sex, and per measurement method).<br>REF_AGE_DAYS = np.array([0, 30, 365, 730, 3650, 6570])<br>REF_MEDIAN   = np.array([130, 140, 120, 110, 90, 80])   # made up<br>REF_SD       = np.array([16, 16, 15, 14, 12, 11])       # made up<br><br>def age_z(value, age_days):<br>    &quot;&quot;&quot;How unusual is this value for a healthy child of this age?&quot;&quot;&quot;<br>    median = np.interp(age_days, REF_AGE_DAYS, REF_MEDIAN)<br>    sd = np.interp(age_days, REF_AGE_DAYS, REF_SD)<br>    return (value - median) / sd<br><br>print(age_z(150, age_days=30))    # 0.625 with these toy numbers: unremarkable<br>print(age_z(150, age_days=6570))  # about 6.4: wildly unusual</pre><p>The review’s <a href="https://pmc.ncbi.nlm.nih.gov/articles/PMC3789232/">web appendix</a> gives centile cut-offs per band, not a median and SD, so age_z won&#39;t take it directly. Interpolate between the published centiles for an approximate percentile, or fit a smooth model such as Cole and Green&#39;s <a href="https://doi.org/10.1002/sim.4780111005">LMS method</a> (curves over age for the median, spread and skew).</p><p>Skew matters: for boys aged 11 to 15 in the Canadian study, the ALP median (247) sits closer to the bottom of the range (113) than the top (438), so a symmetric z-score misleads in the tails. And np.interp quietly clamps ages outside the table to the nearest edge.</p><p>Also check what “upper limit” means: the heart-rate charts use the 1st to 99th centile, and lab reference intervals may use a different cut. Read the methods before you compare them.</p><h3>Gotchas</h3><ul><li><strong>Pick the reference for your question.</strong> “Unusual for this age?” needs a healthy reference. “Page a nurse?” may need centiles from children in hospital, as the <a href="https://doi.org/10.1542/peds.2012-2443">2013 study</a> built.</li><li><strong>Evaluate per age band, not just overall.</strong> A model that’s great on adults and poor on infants can still post a fine overall AUROC. Check alerts against real outcomes, band by band.</li><li><strong>How you measure shifts “normal”.</strong> In the heart-rate review, community readings ran higher than clinic ones, ECG higher than hand counts, and newer studies higher than older ones. If your reference and data were measured differently, your scores inherit the gap.</li><li><strong>Ranges belong to a lab, and to a sex.</strong> ALP ranges depend on the lab and method (<a href="https://www.ncbi.nlm.nih.gov/books/NBK459201/">StatPearls</a>), and in the Canadian data girls’ ALP starts falling around 11, boys’ around 16. Normalise against the lab’s own range for the child’s age and sex.</li><li><strong>Age in days, at each measurement.</strong> “Age 0” lumps a newborn with an 11-month-old, yet the median heart rate climbs from 127 to 145 in the first month. Compute age at each reading, not admission; check de-identified extracts didn’t shrink it to whole years; and for babies born early, check whether the reference expects corrected age (age minus weeks born early).</li><li><strong>Doses need a weight.</strong> Check it exists, is recent, and is in the units you think: kilograms, pounds, or grams for newborns.</li><li><strong>Some extremes are real.</strong> Children can have temporary ALP spikes of up to 30 times the upper limit, called transient hyperphosphatasemia, usually without symptoms (<a href="https://www.ncbi.nlm.nih.gov/books/NBK459201/">StatPearls</a>). A very high value still needs its cause checked, so don’t let an outlier filter delete it as an error, and don’t hard-code it as disease either.</li></ul><h3>The takeaway</h3><p>A number means nothing until you know whose it is.</p><p>Age just happens to be the easiest place to see it. Before you trust a threshold or a feature in a clinical model, ask the shoe-shop question. Whose foot is this, and what else does the number leave out?</p><p>Next time: <strong>Your model has never met a child.</strong> What happens when a model trained on adults is deployed on children.</p><h3>Further reading</h3><p>- <a href="https://pmc.ncbi.nlm.nih.gov/articles/PMC3789232/">The 2011 Lancet review of children’s heart and breathing rates</a> (open access): the centile charts, and how far the guideline ranges were off.</p><p>- <a href="https://doi.org/10.1542/peds.2012-2443">Heart-rate centiles for children in hospital</a> (Pediatrics, 2013): why the right reference depends on the question.</p><p>- <a href="https://doi.org/10.1373/clinchem.2011.177741">CALIPER’s children’s reference ranges for 40 blood markers</a> (Clinical Chemistry, 2012).</p><p>- <a href="https://doi.org/10.1373/clinchem.2015.240515">The Canadian study of 24 blood markers from age 3 to 79</a> (Clinical Chemistry, 2015): where the ALP numbers come from.</p><p>- <a href="https://doi.org/10.1056/NEJMra035092">Developmental pharmacology in infants and children</a> (New England Journal of Medicine, 2003): why children’s bodies handle drugs differently.</p><p><em>Originally published at </em><a href="https://karthick47v2.github.io/blog/2026/children-arent-small-adults/"><em>https://karthick47v2.github.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba48bcc5f493" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parallel Matrix Multiplication]]></title>
            <link>https://medium.com/@mrintrovert/parallel-matrix-multiplication-7e2e0efa64f4?source=rss-a1513e49f9a4------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e2e0efa64f4</guid>
            <category><![CDATA[parallel-computing]]></category>
            <category><![CDATA[high-performace-computing]]></category>
            <category><![CDATA[matrix-multiplication]]></category>
            <category><![CDATA[parallel-processing]]></category>
            <category><![CDATA[openmp]]></category>
            <dc:creator><![CDATA[Karthick T. Sharma]]></dc:creator>
            <pubDate>Mon, 26 Dec 2022 19:12:14 GMT</pubDate>
            <atom:updated>2022-12-26T19:21:46.614Z</atom:updated>
            <content:encoded><![CDATA[<p>Matrix multiplication is a fundamental operation in linear algebra. It is a crucial operation in many mathematical and scientific fields, including computer graphics, machine learning, and engineering. However, this can be computationally expensive and time-consuming, especially when the matrices are large. We can speed it up by sharing the work among multiple cores.</p><p>In this article, I have used OpenMP to parallelize matrix multiplication. OpenMP (Open Multiprocessing) is a popular open-source library for parallel programming in C, C++ and FORTRAN. We are going to analyze the performance of matrix multiplication for squared matrices with dimensions ranging from 100 to 1000 assuming that, you already know what matrix multiplication is.</p><p><strong>NOTE:</strong> As we are only focusing about matrix multiplication, I leave matrix initialization and printing parts up to you. But you can always see the complete implementation <a href="https://github.com/Karthick47v2/parallel-matrix-multiplication">here</a>.</p><h4>Sequential Approach</h4><p>First let’s see naive matrix multiplication implementation where each operation run sequentially.</p><pre>for (short int i = 0; i &lt; MAT_DIMS; i++)<br>    {<br>        for (short int j = 0; j &lt; MAT_DIMS; j++)<br>        {<br>            for (short int k = 0; k &lt; MAT_DIMS; k++)<br>            {<br>                mat[i * MAT_DIMS + j] += matA[i * MAT_DIMS + k] * matB[k * MAT_DIMS + j];<br>            }<br>        }<br>    }</pre><p>The first loop used to iterate over rows of Matrix A and second loop used to iterate over columns of Matrix B. As we know, to get Matrix(i, j) we need to multiply iᵗʰ row of Matrix A with jᵗʰ column of Matrix B. In order to multiply each element we need another loop, which is the 3rd loop in above implementation. The time complexity of this approach is O(n³) which means that executing time grows at a rate of n³ as the size of the matrices increases. Note that I have used 1D array instead of 2D array for matrices as it is likely to be faster since it offers better memory locality, less allocation and deallocation overhead, and it consumes less memory than 2D dynamic arrays.</p><p>There are some algorithms which can be used to optimize and reduce time complexity in sequential manner. For example, Strassen’s matrix multiplication algorithm, faster than naive approach. However, these algorithms can be more complex and may not be always be practical to use in all situations.</p><h4>Parallel Approach</h4><p>To parallelize this operation using OpenMP, we can use the <strong>#pragma omp parallel</strong> directive, which tells the compiler to parallelize the code segment enclosed by it.</p><pre>#pragma omp parallel shared(matA, matB, mat)<br>    {<br>        short int numThreads = omp_get_num_threads();<br>        short int threadNo = omp_get_thread_num();<br><br>        for (short int i = threadNo; i &lt; MAT_DIMS; i += numThreads)<br>        {<br>            for (short int j = 0; j &lt; MAT_DIMS; j++)<br>            {<br>                for (short int k = 0; k &lt; MAT_DIMS; k++)<br>                {<br>                    mat[i * MAT_DIMS + j] += matA[i * MAT_DIMS + k] * matB[k * MAT_DIMS + j];<br>                }<br>            }<br>        }<br>    }</pre><p>The <strong>shared()</strong> clause specifies that the matrices should be shared between threads. <strong>omp_get_num_threads() </strong>will return number of threads participating in parallel execution, and <strong>omp_get_thread_num()</strong> will return thread ID of current thread. Here, we are parallelizing outer loop only, you can see that starting row ID differs for each thread and using<strong> numThreads</strong> to increment loop variable <strong>i</strong> ensures that each thread will access unique rows of Matrix A. Also, we don’t need to consider race condition as each thread updates different memory location in Resultant Matrix.</p><p>Actually, we don’t need to manually divide range for each thread. OpenMP will do all these things by itself for loops if we use <strong>#pragma omp parallel for</strong> directive. Here is an example of how to parallelize matrix multiplication using OpenMP way.</p><pre>#pragma omp parallel for shared(matA, matB, mat)<br>        for (short int i = 0; i &lt; MAT_DIMS; i++)<br>        {<br>            for (short int j = 0; j &lt; MAT_DIMS; j++)<br>            {<br>                for (short int k = 0; k &lt; MAT_DIMS; k++)<br>                {<br>                    mat[i * MAT_DIMS + j] += matA[i * MAT_DIMS + k] * matB[k * MAT_DIMS + j];<br>                }<br>            }<br>        }</pre><p>By using OpenMP to parallelize the matrix multiplication operation, we can take advantage of multiple cores to speed up the computation. This can be especially useful for large matrices, where the computational cost of matrix multiplication can be quite high. But still, we can optimize it further. The major problem with the above approach is, this implementation doesn’t favor cache.</p><h4>Optimized Parallel Approach (Utilizing Row Major)</h4><p>When a process requires some data from memory, usually its adjacent data also copied to cache for faster access. Usually, arrays in C are row major, which means row elements are stored next to each other in memory. So, if we fetch an array element from memory, its adjacent elements will get stored in cache. We are utilizing this for first loop (iterating over row), but not for second loop. Because for each row, we are only using 1 element (multiplying Matrix A’s row by Matrix B’s column). Therefore, we are wasting cached adjacent elements of Matrix B for each column (adding overhead of accessing them directly later). So, in the 3rd approach, we are going to utilize properties of C array.</p><pre>#pragma omp parallel shared(matA, matB, mat)<br>    {<br>        short int numThreads = omp_get_num_threads();<br>        short int threadNo = omp_get_thread_num();<br><br>        unsigned short int temp[MAT_DIMS];<br><br>        for (short int i = threadNo; i &lt; MAT_DIMS; i += numThreads)<br>        {<br>            memset(temp, 0, MAT_DIMS * sizeof(short int));<br>            for (short int j = 0; j &lt; MAT_DIMS; j++)<br>            {<br>                for (short int k = 0; k &lt; MAT_DIMS; k++)<br>                {<br>                    temp[k] += matA[i * MAT_DIMS + j] * matB[j * MAT_DIMS + k];<br>                }<br>            }<br>            memcpy(&amp;mat[i * MAT_DIMS], temp, MAT_DIMS * sizeof(short int));<br>        }<br>    }</pre><p>In the above implementation, instead of directly finding each resultant elements, we are finding all elements in each row of Resultant Matrix and updating it.<strong> </strong>Below shown image will give some insights about what is happening.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LcDjNcnYK15NjfYrHc7j-A.png" /><figcaption>Multiply Matrix A with each row of Matrix B</figcaption></figure><p>If we look into first iteration of outer loop, first row elements of Matrix A will get multiplied by first row of Matrix B which results partial value of first row of Resultant Matrix, then second row of Matrix B and go on. Finally, when all rows of Matrix B gets multiplied by first row of Matrix A, this will result in final output of first row of Resultant Matrix. This operation will happen for all rows of Matrix A.</p><p>Back to the implementation, <strong>memset()</strong> is used to set all elements of <strong>temp</strong> array, which is a row in resultant array, to zero. <strong>memcpy()</strong> is used to copy all elements from <strong>temp</strong> array to a respective row of the resultant array. So, here, we are utilizing the cache as much as possible.</p><h4>Analyze Performance</h4><p>Let’s see the performance of these approaches with varying dimensions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Cuo74OareASBhFmUZNsbCA.png" /><figcaption>Execution time for matrix multiplication of square matrices</figcaption></figure><p>The parallel execution was done using 12 Threads. We can see that parallel execution speeds up the operation when the size of the matrices increase. Also, our optimized method performs better than usual OpenMP parallelization for each case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*hBKtHyJB1cO3hnEvGV5rkA.png" /><figcaption>Execution time vs no. of threads for optimized parallel approach</figcaption></figure><p>From the above graph, we can see that execution time decreases when we increase the number of threads. But keep in mind that parallelizing matrix multiplication is not always straightforward, and it may require some experimentation and optimization to achieve the best performance. Factors such as the size of the matrices, the number of cores available, and the workload balance can all affect the performance of the parallelized matrix multiplication.</p><p>Repo: <a href="https://github.com/Karthick47v2/parallel-matrix-multiplication">https://github.com/Karthick47v2/parallel-matrix-multiplication</a></p><p>To create awesome charts: <a href="https://www.chartblocks.io/">https://www.chartblocks.io/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e2e0efa64f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>