{"id":1113,"date":"2019-12-25T14:24:34","date_gmt":"2019-12-25T04:24:34","guid":{"rendered":"http:\/\/www.moneystock.net\/wp_e\/?p=1113"},"modified":"2019-12-25T14:26:14","modified_gmt":"2019-12-25T04:26:14","slug":"c-performance-improvement-experience","status":"publish","type":"post","link":"https:\/\/moneystock.net\/wp_e\/2019\/12\/25\/c-performance-improvement-experience\/","title":{"rendered":"C# Performance Improvement Experience"},"content":{"rendered":"\n<p>I have a personal code originally wriiten in 10 years ago when I was starting coding in University. The code is basically stock price analysis tool.\u00a0<\/p>\n<p>Recently I started to look at it again and found a few tips to improve the performance calculation and DB access heavy code. Actually, this shouldn&#8217;t be DB access heavy and it is the part of peformance tunning.\u00a0<\/p>\n<p>This is what I have learnt&#8230;<\/p>\n<ul>\n<li>Read\u00a0 all data from DB at the start of the process.\u00a0<\/li>\n<li>Do repeatitive task and calling data in memony.<\/li>\n<li>Utilize multi-thread and don&#8217;t call DB inside multi-threaded task<\/li>\n<li>Once all tasks are completed, update the database at the end if possible at once.\u00a0<\/li>\n<\/ul>\n<p>One more tip<\/p>\n<ul>\n<li>Analyze the coding the profiler, which cleaerly shows what method took the longest. This easily let me focus on where to improve.\u00a0<\/li>\n<\/ul>\n<p>After these improvements, the time took to process the once cycle of simulation decreased from 40 minutes to 10 minutes.\u00a0<\/p>\n<p>A few code change samples are as below.<\/p>\n<ul>\n<li>Read data from DB at the beginning once rather than calling each time when needed.<\/li>\n<\/ul>\n<p>From\u00a0<\/p>\n<pre>public List&lt;StockToAnalyze&gt; ReadPriceToAnalysisForward(string code, int days, DateTime dateToReadFrom)<br \/>{<br \/>    return _marketwatchDbContext<br \/>        .StockToAnalyzes<br \/>        .Where(a =&gt; a.Code == code<br \/>                    &amp;&amp; a.Date &gt;= dateToReadFrom)<br \/>        .OrderBy(a =&gt; a.Date)<br \/>        .Take(days)<br \/>        .AsNoTracking()<br \/>        .ToList();<br \/>}<\/pre>\n<p>Initially, I was calling data from DB each time when stock prices are needed as above.\u00a0<\/p>\n<p>\u00a0<\/p>\n<p>To\u00a0<\/p>\n<pre><code><span class=\"pl-smi\"><span class=\"pl-k\">private<\/span> <span class=\"pl-k\">readonly<\/span> <span class=\"pl-en\">List<\/span>&lt;<span class=\"pl-en\">StockToAnalyze<\/span>&gt; _stockPrices;<\/span><\/code><br \/><br \/><code><span class=\"pl-smi\">_stockPrices<\/span> <span class=\"pl-k\">=<\/span> <span class=\"pl-smi\">_marketwatchDbContext<\/span>.<span class=\"pl-smi\">StockToAnalyzes<\/span>.<span class=\"pl-en\">AsNoTracking<\/span>().<span class=\"pl-en\">ToList<\/span>();<br \/><br \/>public List&lt;StockToAnalyze&gt; ReadPriceToAnalysisForward(string code, int days, DateTime dateToReadFrom)<br \/>{<br \/>    return _stockPrices<br \/>        .Where(a =&gt; a.Code == code<br \/>                    &amp;&amp; a.Date &gt;= dateToReadFrom)<br \/>        .OrderBy(a =&gt; a.Date)<br \/>        .Take(days)<br \/>        .ToList();<br \/>}<\/code><\/pre>\n<p>In the improved code, stock prices are loaded in constructor once and the variable, _stockPrices, was used in the private method.\u00a0<\/p>\n<p>\u00a0<\/p>\n<ul>\n<li>Print debugging content in debugging console rather than conole output. Because console output slows down the process, debugging content only useful when debugging it.\u00a0<\/li>\n<\/ul>\n<p>Before<\/p>\n<pre><span class=\"pl-smi x x-first x-last\">Console<\/span>.<span class=\"pl-en\">WriteLine<\/span>(<span class=\"pl-s\"><span class=\"pl-pds\">$\"<\/span>Correlation coefficient: {<span class=\"pl-smi\">leaderInPair<\/span>.<span class=\"pl-smi\">Coefficient<\/span>}<span class=\"pl-pds\">\"<\/span><\/span>);<\/pre>\n<p>After<\/p>\n<pre><span class=\"pl-smi x x-first x-last\">Debug<\/span>.<span class=\"pl-en\">WriteLine<\/span>(<span class=\"pl-s\"><span class=\"pl-pds\">$\"<\/span>Correlation coefficient: {<span class=\"pl-smi\">leaderInPair<\/span>.<span class=\"pl-smi\">Coefficient<\/span>}<span class=\"pl-pds\">\"<\/span><\/span>);<\/pre>\n<p>\u00a0<\/p>\n<ul>\n<li>Sort once when loading the data. After profiling, I could noticed that repeatitive sorting is very costly even though it happens in the memery. After seprating this point in a sample code, it looks too obivous, it can require a bit of investigation to find where to improve.\u00a0<\/li>\n<\/ul>\n<p>Before<\/p>\n<pre><code><span class=\"pl-smi\"><span class=\"pl-k\">private<\/span> <span class=\"pl-k\">readonly<\/span> <span class=\"pl-en\">List<\/span>&lt;<span class=\"pl-en\">StockToAnalyze<\/span>&gt; _stockPrices;<\/span><\/code><br \/><br \/><code><span class=\"pl-smi\">_stockPrices<\/span> <span class=\"pl-k\">=<\/span> <span class=\"pl-smi\">_marketwatchDbContext<\/span>.<span class=\"pl-smi\">StockToAnalyzes<\/span>.<span class=\"pl-en\">AsNoTracking<\/span>().<span class=\"pl-en\">ToList<\/span>();<\/code><br \/><br \/>public List&lt;StockToAnalyze&gt; ReadPriceToAnalysisForward(string code, int days, DateTime dateToReadFrom)<br \/>{<br \/>return _stockPrices<br \/>.Where(a =&gt; a.Code == code<br \/>&amp;&amp; a.Date &gt;= dateToReadFrom)<br \/>.OrderBy(a =&gt; a.Date)<br \/>.Take(days)<br \/>.ToList();<br \/>}<\/pre>\n<p>After<\/p>\n<pre><code><span class=\"pl-smi\"><span class=\"pl-k\">private<\/span> <span class=\"pl-k\">readonly<\/span> <span class=\"pl-en\">List<\/span>&lt;<span class=\"pl-en\">StockToAnalyze<\/span>&gt; _stockPrices;<\/span><\/code><br \/><br \/><code><span class=\"pl-smi\">_stockPrices<\/span> <span class=\"pl-k\">=<\/span> <span class=\"pl-smi\">_marketwatchDbContext<\/span>.<span class=\"pl-smi\">StockToAnalyzes<\/span>.<span class=\"pl-en\">AsNoTracking<\/span>()<br \/>    .OrderBy(a =&gt; a.Date).<span class=\"pl-en\">ToList<\/span>();<\/code><br \/><br \/>public List&lt;StockToAnalyze&gt; ReadPriceToAnalysisForward(string code, int days, DateTime dateToReadFrom)<br \/>{<br \/>return _stockPrices<br \/>.Where(a =&gt; a.Code == code<br \/>&amp;&amp; a.Date &gt;= dateToReadFrom)<br \/>.Take(days)<br \/>.ToList();<br \/>}<\/pre>\n<p>\u00a0<\/p>\n<ul>\n<li>Use multi-thread. In this case, theadpool can be very useful. This reduced the processing time in half.\u00a0<\/li>\n<\/ul>\n<p>Before<\/p>\n<pre>private IterateSimulationAsync(DateTime investDay, List&lt;string&gt; codes)<br \/>{<br \/>    var simulator = new Simulator(_logger, _marketWatchRepository, codes)<br \/>    {<br \/>        StartDay = investDay,<br \/>    };<br \/>    simulator.Initialize();<br \/><br \/>    var strategies = GetPotentialStrategies(_limit).ToList();<br \/><br \/>    var strategyResults = new List&lt;Strategy&gt;();<br \/>    foreach (var strategy in strategies)<br \/>    {<br \/>        strategyResults.Add(simulator.Run(strategy));<br \/>    }<br \/>}<\/pre>\n<p>After<\/p>\n<pre>private IterateSimulationAsync(DateTime investDay, List&lt;string&gt; codes)<br \/>{<br \/>    var simulator = new Simulator(_logger, _marketWatchRepository, codes)<br \/>    {<br \/>        StartDay = investDay,<br \/>    };<br \/>    simulator.Initialize();<br \/><br \/>    var strategies = GetPotentialStrategies(_limit).ToList();<br \/><br \/>    \/\/ Multi Threading<br \/>    ThreadPool.SetMinThreads(Settings.Default.MinNumberOfThread, Settings.Default.MinNumberOfThread);<br \/>    ThreadPool.SetMaxThreads(Settings.Default.MaxNumberOfThread, Settings.Default.MaxNumberOfThread);<br \/><br \/>    var strategyResults = new List&lt;Strategy&gt;();<br \/>    foreach (var strategy in strategies)<br \/>    {<br \/>        Action&lt;Strategy&gt; resultCallback = (result) =&gt;<br \/>        {<br \/>            strategyResults.Add(result);<br \/>            Interlocked.Decrement(ref _threadCounter);<br \/>        };<br \/><br \/>        Interlocked.Increment(ref _threadCounter);<br \/>        <br \/>        WaitCallback workItem = (input) =&gt;<br \/>        {<br \/>            var result = simulator.Run(input);<br \/>            resultCallback(result);<br \/>        };<br \/><br \/>        ThreadPool.QueueUserWorkItem(workItem, strategy);<br \/>    }<br \/><br \/>    while (_threadCounter != 0)<br \/>    {<br \/>        \/\/ wait until all thread is finished.<br \/>    }<br \/>}<\/pre>\n<p>Next steps to test for performance improvement would be converting this to .Net core app or coding in F#. or pararell processing through mulitple computers. What else can potentially increase the performance more?\u00a0<\/p>\n<p>\u00a0<\/p>\n","protected":false},"excerpt":{"rendered":"<p>I have a personal code originally wriiten in 10 years ago when I was starting coding in University. The code is basically stock price analysis tool.\u00a0 Recently I started to look at it again and found a few tips to improve the performance calculation and DB access heavy code. Actually, this shouldn&#8217;t be DB access&hellip; <a class=\"more-link\" href=\"https:\/\/moneystock.net\/wp_e\/2019\/12\/25\/c-performance-improvement-experience\/\">Continue reading <span class=\"screen-reader-text\">C# Performance Improvement Experience<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[548,193],"tags":[95,560,195,561],"class_list":["post-1113","post","type-post","status-publish","format-standard","hentry","category-c","category-performance","tag-c","tag-multithreading","tag-performance","tag-profiling","entry"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/moneystock.net\/wp_e\/wp-json\/wp\/v2\/posts\/1113","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/moneystock.net\/wp_e\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/moneystock.net\/wp_e\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/moneystock.net\/wp_e\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/moneystock.net\/wp_e\/wp-json\/wp\/v2\/comments?post=1113"}],"version-history":[{"count":3,"href":"https:\/\/moneystock.net\/wp_e\/wp-json\/wp\/v2\/posts\/1113\/revisions"}],"predecessor-version":[{"id":1116,"href":"https:\/\/moneystock.net\/wp_e\/wp-json\/wp\/v2\/posts\/1113\/revisions\/1116"}],"wp:attachment":[{"href":"https:\/\/moneystock.net\/wp_e\/wp-json\/wp\/v2\/media?parent=1113"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/moneystock.net\/wp_e\/wp-json\/wp\/v2\/categories?post=1113"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/moneystock.net\/wp_e\/wp-json\/wp\/v2\/tags?post=1113"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}