<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Igor Ostrovsky Blogging &#187; Cool Stuff</title>
	<atom:link href="http://igoro.com/archive/category/cool-stuff/feed/" rel="self" type="application/rss+xml" />
	<link>http://igoro.com</link>
	<description>On programming, technology, and random things of interest</description>
	<lastBuildDate>Fri, 23 Jul 2010 05:24:22 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Graphs, trees, and origins of humanity</title>
		<link>http://igoro.com/archive/graphs-trees-and-origins-of-humanity/</link>
		<comments>http://igoro.com/archive/graphs-trees-and-origins-of-humanity/#comments</comments>
		<pubDate>Fri, 02 Jul 2010 05:44:18 +0000</pubDate>
		<dc:creator>Igor Ostrovsky</dc:creator>
				<category><![CDATA[Cool Stuff]]></category>

		<guid isPermaLink="false">http://igoro.com/?p=621</guid>
		<description><![CDATA[Imagine that 90,000 years ago, every man alive at the time picked a different last name. Assuming that last names are inherited from father to son, how many different last names do you think there would be today? It turns out that there would be only one last name! Similarly, imagine that 200,000 years ago, [...]]]></description>
			<content:encoded><![CDATA[<p>Imagine that 90,000 years ago, every man alive at the time picked a different last name. Assuming that last names are inherited from father to son, how many different last names do you think there would be today?</p>
<p>It turns out that there would be <strong>only one </strong>last name!</p>
<p>Similarly, imagine that 200,000 years ago, every woman alive picked a different secret word, and told the secret word to her daughters. And, the female descendants would follow this tradition – a mother would always pass her secret word to her daughters.</p>
<p>As you might guess, today there would be <strong>only one </strong>secret word in circulation.</p>
<p>The man whose last name all men would carry is called “Y-chromosomal Adam” and the woman whose secret word all women would know is “Mitochondrial Eve”. The names come from the fact that Y chromosome is a piece of DNA inherited from father to son (just like last names), and mitochondrial DNA is inherited from mother to children (just like the hypothetical secret words).</p>
<h3>Why the convergence?</h3>
<p>So, how likely is it that one last name and one secret word will eventually come to dominate? Given enough time, it is virtually guaranteed, under some assumptions (e.g., the population does not become separated).</p>
<p>Here is a simulation of how last names of five men could flow through six generations:</p>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://igoro.com/wordpress/wp-content/uploads/2010/07/image5.png" width="305" height="265" /></p>
<p>After six generations, the last name shown as green is the only last name around, purely by chance! In biology, this random effect is called <a href="http://en.wikipedia.org/wiki/Genetic_drift">genetic drift</a>.</p>
<p>And, the convergence does not only happen for small populations. Here are the numbers that I got by simulating different population sizes:</p>
<table border="1" cellspacing="0" cellpadding="2" width="210">
<tbody>
<tr>
<td valign="top" width="78"><strong>Population</strong></td>
<td valign="top" width="130"><strong>Generations to convergence</strong></td>
</tr>
<tr>
<td valign="top" width="78">10</td>
<td valign="top" width="130">23</td>
</tr>
<tr>
<td valign="top" width="78">50</td>
<td valign="top" width="130">73</td>
</tr>
<tr>
<td valign="top" width="78">100</td>
<td valign="top" width="130">239</td>
</tr>
<tr>
<td valign="top" width="78">500</td>
<td valign="top" width="130">891</td>
</tr>
<tr>
<td valign="top" width="78">1000</td>
<td valign="top" width="130">1395</td>
</tr>
<tr>
<td valign="top" width="78">5000</td>
<td valign="top" width="130">7312</td>
</tr>
<tr>
<td valign="top" width="78">10000</td>
<td valign="top" width="130">13491</td>
</tr>
</tbody>
</table>
<p>&#160;</p>
<p>Here is the implementation of this simulation:</p>
<pre class="code"><span style="color: blue">static int </span>MitochondrialEve(<span style="color: blue">int </span>populationSize)
{
    <span style="color: #2b91af">Random </span>random = <span style="color: blue">new </span><span style="color: #2b91af">Random</span>();

    <span style="color: blue">int </span>generations = 0;
    <span style="color: blue">int</span>[] cur = <span style="color: blue">new int</span>[populationSize];
    <span style="color: blue">for </span>(<span style="color: blue">int </span>i = 0; i &lt; populationSize; i++) cur[i] = i;

    <span style="color: blue">for </span>( ; cur.Max() != cur.Min(); generations++)
    {
        <span style="color: blue">int</span>[] next = <span style="color: blue">new int</span>[populationSize];
        <span style="color: blue">for </span>(<span style="color: blue">int </span>i = 0; i &lt; next.Length; i++)
        {
            next[i] = cur[random.Next(populationSize)];
        }
        cur = next;
    }

    <span style="color: blue">return </span>generations;
}</pre>
<p>This simulation is not a sophisticated model of a human population, but it is sufficient for the purposes of illustrating genetic drift. It assumes that every man has on average one son, with a standard deviation of roughly one, and a binomial probability distribution.</p>
<p>By the way, the Y-chromosomal Adam lived roughly 60,000–90,000 years ago, while Eve lived roughly 200,000 years ago. The reason why genetic drift acted faster for men is that men have a larger variation in the number of offspring – one man can have many more children than one woman.</p>
<p>UPDATE: Based on comments at Hacker News and Reddit, some readers are dissatisfied with the assumption of a fixed population size. Of course, human population grew over the ages, but there were also periods when it shrank, sometimes a lot. For example, roughly 70,000 years ago, the human population may have dropped down to thousands of individuals (<a href="http://en.wikipedia.org/wiki/Toba_catastrophe_theory">1</a>, <a href="https://genographic.nationalgeographic.com/genographic/dawn.html">2</a>). So, a fixed population size is a reasonable simplification for my example.</p>
<h3>The roles of Mitochondrial Eve and Y-chromosomal Adam</h3>
<p>One noteworthy fact about Mitochondrial Eve and Y-chromosomal Adam is that their positions in the history are not as special as they may first appear. Let’s take a look at this in more depth.</p>
<p>Tracing from me, I can follow a path of paternal ancestry all the way to Y-chromosomal Adam:</p>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://igoro.com/wordpress/wp-content/uploads/2010/07/image6.png" width="703" height="51" />&#160;</p>
<p>If I only trace the male ancestry, there is exactly one path that starts at me, and that path leads to Y-chromosomal Adam. You could start the diagram at any man alive today and you’d get a similar picture, with the lineage finally reaching the Y-chromosomal Adam.</p>
<p>However, if I trace ancestry via both parents, the number of ancestors explodes. I have two parents, four grandparents, eight great grandparents, and so forth. The number of ancestors in each generation grows exponentially, although that cannot continue for long. If all ancestors in each generations were distinct, I would have more than 1 billion ancestors just 30 generations back, so the tree certainly has to start collapsing into a directed acyclic graph by then.</p>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://igoro.com/wordpress/wp-content/uploads/2010/07/image7.png" width="361" height="235" /></p>
<p>Tracing ancestry through both parents, there are many paths to follow, and each generation of ancestors contains a lot of people. Some of those paths will reach Y-chromosomal Adam, but other paths will reach <strong>other men</strong> <strong>in his generation</strong>. Similarly, some paths will reach Mitochondrial Eve, but other paths will reach <strong>other women in her generation</strong>.</p>
<h3>Most recent common ancestor</h3>
<p>So, Mitochondrial Eve only has a special position with respect to the mother-daughter relationships, and Y-chromosomal Adam only with respect to the father-son relationships.</p>
<p>What if you consider all types of ancestry, father-son, father-daughter, mother-son and mother-daughter? In the resulting directed acyclic graph, neither the Y-chomosomal Adam nor the Mitochondrial Eve appear in a special position. In fact, in the combined graph, the most recent ancestor of all today’s people lived <strong>much </strong>later than Y-chromosomal Adam. The most recent ancestor is estimated to have lived roughly 15,000 to 5,000 years ago.</p>
<p>One way to visualize the relationship between Mitochondrial Eve, Y-chromosomal Adam, and the Most Recent Common Ancestor (MRCA) is to look at a small genealogy diagram with just a few people:</p>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://igoro.com/wordpress/wp-content/uploads/2010/07/image8.png" width="328" height="556" /></p>
<p>For the last generation consisting of just four people, this graph shows the Mitochondrial Eve, the Y-chromosomal Adam, and the most recent common ancestors (a couple in this example, but could also be one man or one woman). Adam is at the root of the blue tree, Eve is at the root of the red tree, and the most recent common ancestors are much lower in the graph.</p>
<h3>The dating of Y-Adam and M-Eve</h3>
<p>Finally, I’ll briefly give you an idea on how biologists calculate when Mitochondrial Eve and Y-chromosomal Adam lived.</p>
<p>The dating is based on DNA analysis. Changes in DNA accumulate at a certain rate that depends on various factors – region of the DNA, the species, population size, etc. To date Mitochondrial Eve, biologists calculate an estimate of the mitochondrial DNA (mtDNA) mutation rate. Then, they look at how much mtDNA varies between today’s women, and then calculate how long it would take to achieve that degree of variation.</p>
<p>Another interesting fact is that the titles of Mitochondrial Eve and Y-chromosomal Adam are not permanent, but instead are reassigned over time. For example, the woman who we call “Mitochondrial Eve” today did not hold that title during her lifetime. Instead, there was another unknown woman who was the most recent common matrilineal ancestor of all women alive at Eve’s time.</p>
<h3>Final words</h3>
<p>I hope you enjoyed the article. I originally learned about Y-chromosomal Adam and Mitochondrial Eve from reading <a href="http://www.amazon.com/dp/014303832X/">Before the Dawn</a>, and immediately knew I had to blog about them from a programmer’s perspective. If you want to read more on the topic, the Wikipedia page on <a href="http://en.wikipedia.org/wiki/Mitochondrial_eve">Mitochondrial Eve</a> is a good start.</p>
<div style="border-bottom: black 1px solid; border-left: black 1px solid; padding-bottom: 10px; background-color: #f0f0ff; margin-top: 20px; padding-left: 10px; padding-right: 10px; margin-bottom: 20px; margin-left: 10px; border-top: black 1px solid; border-right: black 1px solid; padding-top: 10px">
<p>Read more of my articles:</p>
<p><a href="http://igoro.com/archive/fast-and-slow-if-statements-branch-prediction-in-modern-processors/">Fast and slow if statements: branch prediction in modern processors</a></p>
<p><a href="http://igoro.com/archive/human-heart-is-a-turing-machine-research-on-xbox-360-shows-wait-what/">Human heart is a Turing machine, research on XBox 360 shows. Wait, what?</a></p>
<p><a href="http://igoro.com/archive/self-printing-game-of-life-in-c/">Self-printing Game of Life in C#</a></p>
<p>And if you like my blog, <a href="http://igoro.com/feed/">subscribe</a>!</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://igoro.com/archive/graphs-trees-and-origins-of-humanity/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Fast and slow if-statements: branch prediction in modern processors</title>
		<link>http://igoro.com/archive/fast-and-slow-if-statements-branch-prediction-in-modern-processors/</link>
		<comments>http://igoro.com/archive/fast-and-slow-if-statements-branch-prediction-in-modern-processors/#comments</comments>
		<pubDate>Sat, 15 May 2010 21:11:32 +0000</pubDate>
		<dc:creator>Igor Ostrovsky</dc:creator>
				<category><![CDATA[Cool Stuff]]></category>

		<guid isPermaLink="false">http://igoro.com/?p=579</guid>
		<description><![CDATA[Did you know that the performance of an if-statement depends on whether its condition has a predictable pattern? If the condition is always true or always false, the branch prediction logic in the processor will pick up the pattern. On the other hand, if the pattern is unpredictable, the if-statement will be much more expensive. [...]]]></description>
			<content:encoded><![CDATA[<p>Did you know that the performance of an if-statement depends on whether its condition has a predictable pattern? If the condition is always true or always false, the branch prediction logic in the processor will pick up the pattern. On the other hand, if the pattern is unpredictable, the if-statement will be much more expensive. In this article, I’ll explain why today’s processors behave this way.</p>
<p>Let’s measure the performance of this loop with different conditions:</p>
<pre class="code"><span style="color: blue">for </span>(<span style="color: blue">int </span>i = 0; i &lt; max; i++) <span style="color: blue">if </span>(&lt;condition&gt;) sum++;</pre>
<p>Here are the timings of the loop with different True-False patterns:</p>
<table border="1" cellspacing="0" cellpadding="2" width="579">
<tbody>
<tr>
<td valign="top" width="277"><strong>Condition</strong></td>
<td valign="top" width="216"><strong>Pattern</strong></td>
<td valign="top" width="108"><strong>Time (ms)</strong></td>
</tr>
<tr>
<td valign="top" width="286">(i &amp; 0&#215;80000000) == 0</td>
<td valign="top" width="216">T repeated</td>
<td valign="top" width="108">322</td>
</tr>
<tr>
<td valign="top" width="284">(i &amp; 0xffffffff) == 0</td>
<td valign="top" width="216">F repeated</td>
<td valign="top" width="108">276</td>
</tr>
<tr>
<td valign="top" width="281">(i &amp; 1) == 0</td>
<td valign="top" width="216">TF alternating</td>
<td valign="top" width="108">760</td>
</tr>
<tr>
<td valign="top" width="279">(i &amp; 3) == 0</td>
<td valign="top" width="216">TFFFTFFF…</td>
<td valign="top" width="108">513</td>
</tr>
<tr>
<td valign="top" width="277">(i &amp; 2) == 0</td>
<td valign="top" width="216">TTFFTTFF…</td>
<td valign="top" width="108">1675</td>
</tr>
<tr>
<td valign="top" width="276">(i &amp; 4) == 0</td>
<td valign="top" width="216">TTTTFFFFTTTTFFFF…</td>
<td valign="top" width="108">1275</td>
</tr>
<tr>
<td valign="top" width="276">(i &amp; <span>8</span>) == 0</td>
<td valign="top" width="216">8T 8F 8T 8F …</td>
<td valign="top" width="108">752</td>
</tr>
<tr>
<td valign="top" width="275">(i &amp; 16) == 0</td>
<td valign="top" width="216">16T 16F 16T 16F …</td>
<td valign="top" width="108">490</td>
</tr>
</tbody>
</table>
<p>A “bad” true-false pattern can make an if-statement up to <strong>six times slower </strong>than a “good” pattern! Of course, which pattern is good and which is bad depends on the exact instructions generated by the compiler and on the specific processor.</p>
<h3>Let’s look at the processor counters</h3>
<p>One way to understand how the processor used its time is to look at the hardware counters. To help with performance tuning, modern processors track various counters as they execute code: the number of instructions executed, the number of various types of memory accesses, the number of branches encountered, and so forth. To read the counters, you’ll need a tool such as <a href="http://msdn.microsoft.com/en-us/library/bb385772.aspx">the profiler in Visual Studio 2010 Premium or Ultimate</a>, <a href="http://developer.amd.com/cpu/CodeAnalyst/codeanalystwindows/Pages/default.aspx">AMD Code Analyst</a> or <a href="http://software.intel.com/en-us/intel-vtune/">Intel VTune</a>.</p>
<p>To verify that the slowdowns we observed were really due to the if-statement performance, we can look at the Mispredicted Branches counter:</p>
<p><a href="http://igoro.com/wordpress/wp-content/uploads/2010/05/image.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://igoro.com/wordpress/wp-content/uploads/2010/05/image_thumb.png" width="484" height="563" /></a></p>
<p>The worst pattern (TTFFTTFF…) results in 774 branch mispredictions, while the good patterns only get around 10. No wonder that the bad case took the longest 1.67 seconds, while the good patterns only took around 300ms!</p>
<p>Let’s take a look at what “branch prediction” does, and why it has a major impact on the processor performance.</p>
<h3>What’s the role of branch prediction?</h3>
<p>To explain what branch prediction is and why it impacts the performance numbers, we first need to take a look at how modern processors work. To complete each instruction, the CPU goes through these (and more) stages:</p>
<p>1. <strong>Fetch</strong>: Read the next instruction.</p>
<p>2. <strong>Decode</strong>: Determine the meaning of the instruction.</p>
<p>3. <strong>Execute</strong>: Perform the real ‘work’ of the instruction.</p>
<p>4. <strong>Write-back</strong>: Store results into memory.</p>
<p>An important optimization is that the stages of the pipeline can process different instructions at the same time. So, as one instruction is getting fetched, a second one is being decoded, a third is executing and the results of fourth are getting written back. Modern processors have pipelines with 10 &#8211; 31 stages (e.g., Pentium 4 Prescott has <a href="http://www.tomshardware.com/reviews/intel,751-5.html">31 stages</a>), and for optimum performance, it is very important to keep all stages as busy as possible.</p>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="500px-Pipeline,_4_stage_svg" border="0" alt="500px-Pipeline,_4_stage_svg" src="http://igoro.com/wordpress/wp-content/uploads/2010/05/500pxPipeline_4_stage_svg.png" width="500" height="479" />&#160; <br /><font size="1">Image from </font><a title="http://commons.wikimedia.org/wiki/File:Pipeline,_4_stage.svg" href="http://commons.wikimedia.org/wiki/File:Pipeline,_4_stage.svg"><font size="1">http://commons.wikimedia.org/wiki/File:Pipeline,_4_stage.svg</font></a></p>
<p>Branches (i.e. conditional jumps) present a difficulty for the processor pipeline. After fetching a branch instruction, the processor needs to fetch the next instruction. But, there are <strong>two possible</strong> “next” instructions! The processor won’t be sure which instruction is the next one until the branching instruction makes it to the end of the pipeline.</p>
<p>Instead of stalling the pipeline until the branching instruction is fully executed, modern processors attempt to <strong>predict</strong> whether the jump will or will not be taken. Then, the processor can fetch the instruction that it thinks is the next one. If the prediction turns out wrong, the processor will simply discard the partially executed instructions that are in the pipeline. See the Wikipedia page on <a href="http://en.wikipedia.org/wiki/Branch_prediction#Implementation">branch predictor implementation</a> for some typical techniques used by processors to collect and interpret branch statistics.</p>
<p>Modern branch predictors are good at predicting simple patterns: all true, all false, true-false alternating, and so on. But if the pattern happens to be something that throws off the branch predictor, the performance hit will be significant. Thankfully, most branches have <strong>easily predictable</strong> patterns, like the two examples highlighted below:</p>
<pre class="code"><span style="color: blue">int </span>SumArray(<span style="color: blue">int</span>[] array) {
    <span style="color: blue">if </span>(<span style="background-color: #e0e0e0">array == <span style="color: blue">null</span></span>) <span style="color: blue">throw new </span><span style="color: #2b91af">ArgumentNullException</span>(<span style="color: #a31515">&quot;array&quot;</span>);

    <span style="color: blue">int </span>sum=0;
    <span style="color: blue">for</span>(<span style="color: blue">int </span>i=0; <span style="background-color: #e0e0e0">i&lt;array.Length</span>; i++) sum += array[i];
    <span style="color: blue">return </span>sum;
}</pre>
<p>The first highlighted condition validates the input, and so the branch will be taken only very rarely. The second highlighted condition is a loop termination condition. This will also almost always go one way, unless the arrays processed are extremely short. So, in these cases – as in most cases – the processor branch prediction logic will be effective at preventing stalls in the processor pipeline.</p>
<h3>Updates and Clarifications</h3>
<p>This article got picked up by <a href="http://reddit.com/">reddit</a>, and got a fair bit of attention in the <a href="http://www.reddit.com/r/programming/comments/c7ues/fast_and_slow_ifstatements_branch_prediction_in/">reddit comments</a>. I’ll respond to the questions, comments and criticisms below.</p>
<p>First, regarding the comments that optimizing for branch prediction is generally a bad idea: I agree. I do not argue anywhere in the article that you should try to write your code to optimize for branch prediction. For the vast majority of high-level code, I can’t even imagine how you’d do that.</p>
<p>Second, there was a concern whether the executed instructions for different cases differ in something else other than the constant value. They don’t – I looked at the JIT-ted assembly. If you’d like to see the JIT-ted assembly code or the C# source code, send me an email and I’ll send them back. (I am not posting the code here because I don’t want to blow up this update.)</p>
<p>Third, another question was on the surprisingly poor performance of the TTFF* pattern. The TTFF* pattern has a short period, and as such should be an easy case for the branch prediction algorithms.</p>
<p>However, the problem is that modern processors don’t track history for each branching instruction separately. Instead, they either track global history of all branches, or they have several history slots, each potentially shared by multiple branching instructions. Or, they can use some combination of these tricks, together with other techniques.</p>
<p>So, the TTFF pattern in the if-statement may not be TTFF by the time it gets to the branch predictor. It may get interleaved with other branches (there are 2 branching instructions in the body of a for-loop), and possibly approximated in other ways too. But, I don’t claim to be an expert on what precisely each processor does, and if someone reading this has an authoritative reference to how different processors behave (esp. Intel Core2 that I tested on), please let me know in comments.</p>
<p>&#160;</p>
<div style="border-bottom: black 1px solid; border-left: black 1px solid; padding-bottom: 10px; background-color: #f0f0ff; margin-top: 20px; padding-left: 10px; padding-right: 10px; margin-bottom: 20px; margin-left: 10px; border-top: black 1px solid; border-right: black 1px solid; padding-top: 10px">
<p>Read more of my articles:</p>
<p><a href="http://igoro.com/archive/gallery-of-processor-cache-effects/">Gallery of processor cache effects</a></p>
<p><a href="http://igoro.com/archive/how-gpu-came-to-be-used-for-general-computation/">How GPU came to be used for general computation</a></p>
<p><a href="http://igoro.com/archive/what-really-happens-when-you-navigate-to-a-url/">What really happens when you navigate to a URL</a></p>
<p><a href="http://igoro.com/archive/self-printing-game-of-life-in-c/">Self-printing Game of Life in C#</a></p>
<p>And if you like my blog, <a href="http://igoro.com/feed/">subscribe</a>!</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://igoro.com/archive/fast-and-slow-if-statements-branch-prediction-in-modern-processors/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		</item>
		<item>
		<title>How GPU came to be used for general computation</title>
		<link>http://igoro.com/archive/how-gpu-came-to-be-used-for-general-computation/</link>
		<comments>http://igoro.com/archive/how-gpu-came-to-be-used-for-general-computation/#comments</comments>
		<pubDate>Fri, 12 Mar 2010 09:30:56 +0000</pubDate>
		<dc:creator>Igor Ostrovsky</dc:creator>
				<category><![CDATA[Cool Stuff]]></category>

		<guid isPermaLink="false">http://igoro.com/?p=518</guid>
		<description><![CDATA[The story of how GPU came to be used for high-performance computation is pretty cool. Hardware heavily optimized for graphics turned out to be useful for another use: certain types of high-performance computations. In this article, I will explore how and why this happened, and summarize the state of general computation on GPUs today. Programmable [...]]]></description>
			<content:encoded><![CDATA[</p>
<p>The story of how GPU came to be used for high-performance computation is pretty cool. Hardware heavily optimized for graphics turned out to be useful for another use: certain types of high-performance computations. In this article, I will explore how and why this happened, and summarize the state of general computation on GPUs today.</p>
<h3>Programmable graphics</h3>
<p>The first step towards computation on the GPU was introduction of programmable shaders. Both DirectX and OpenGL added support for programmable shaders roughly a decade ago, giving game designers more freedom to create custom graphics effects. Instead of just composing pre-canned effects, graphic artists can now write little programs that execute <strong>directly on the GPU</strong>. As of DirectX 8, they can specify two types of shader programs for every object in the scene: a vertex shader and a pixel shader.</p>
<p>A <strong>vertex shader</strong> is a function invoked on every vertex in the 3D object. The function transforms the vertex and returns its position relative to the camera view. By transforming vertices, vertex shaders help implement realistic skin, clothes, facial expressions, and similar effects.</p>
<p>A <strong>pixel shader</strong> is a function invoked on every pixel covered by a particular object and returns the color of the pixel. To compute the output color, the pixel shader can use a variety of optional inputs: XY-position on the screen, XYZ-position in the scene, position in the texture, the direction of the surface (i.e., the normal vector), etc. Pixel shader can also read textures, bump maps, and other inputs.</p>
<p>Here is a simple scene, rendered with six different pixel shaders applied to the teapot:</p>
<p>&#160;<a href="http://igoro.com/wordpress/wp-content/uploads/2010/03/image5.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://igoro.com/wordpress/wp-content/uploads/2010/03/image_thumb.png" width="402" height="279" /></a> </p>
<p><strong>A</strong> always returns the same color. <strong>B</strong> varies the color based on the screen Y-coordinate. <strong>C</strong> sets the color depending on the XYZ screen coordinates. <strong>D</strong> sets the color proportionally to the cosine of the angle between the surface normal and the light direction (“diffuse lighting”). <strong>E</strong> uses a slightly more complex lighting model and a texture, and <strong>F</strong> also adds a bump map.</p>
<div style="border-bottom: black 1px solid; border-left: black 1px solid; padding-bottom: 10px; background-color: #f0f0ff; margin-top: 20px; padding-left: 10px; padding-right: 10px; margin-bottom: 20px; margin-left: 10px; border-top: black 1px solid; border-right: black 1px solid; padding-top: 10px">
<p>If you are curious how lighting shaders are implemented, check out GamaSutra’s <a href="http://www.gamasutra.com/features/20030418/engel_01.shtml">Implementing Lighting Models With HLSL</a>.</p>
</p></div>
<h3>Realization: shaders can be used for computation!</h3>
<p>Let’s take a look at a simple pixel shader that just blurs a texture. This shader is implemented in HLSL (a DirectX shader language):</p>
<pre class="code">float4 ps_main( float2 t: TEXCOORD0 ) : COLOR0
{
   float dx = 2/fViewportWidth;
   float dy = 2/fViewportHeight;
   return
      0.2 * tex2D( baseMap, t ) +
      0.2 * tex2D( baseMap, t + float2(dx, 0) ) +
      0.2 * tex2D( baseMap, t + float2(-dx, 0) ) +
      0.2 * tex2D( baseMap, t + float2(0, dy) ) +
      0.2 * tex2D( baseMap, t + float2(0, -dy) );
}</pre>
<p>The texture blur has this effect:</p>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="blur" border="0" alt="blur" src="http://igoro.com/wordpress/wp-content/uploads/2010/03/blur.jpg" width="350" height="170" />&#160;</p>
<p>This is not exactly a breath-taking effect, but the interesting part is that simulations of <strong>car crashes</strong>, <strong>wind tunnels</strong> and <strong>weather patterns</strong> all follow this basic pattern of computation! All of these simulations are computations on a grid of points. Each point has one or more quantities associated with it: temperature, pressure, velocity, force, air flow, etc. In each iteration of the simulation, the <strong>neighboring points interact</strong>: temperatures and pressures are equalized, forces are transferred, grid is deformed, and so forth. Mathematically, the programs that run these simulations are partial differential equation (<strong>PDE</strong>) solvers.</p>
<p>As a trivial example, here is a simple simulation of <strong>heat dissipation</strong>. In each iteration, the temperature of each grid point is recomputed as an average over its nearest neighbors:</p>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="temperature" border="0" alt="temperature" src="http://igoro.com/wordpress/wp-content/uploads/2010/03/temperature.png" width="597" height="122" /> </p>
<p>It is hard to overlook the fact that an iteration of this simulation is nearly identical to the blur operation. Hardware highly optimized for running pixel shaders will be able to run this simulation very fast. And, after years of refinement and challenges from latest and greatest games, GPUs became very efficient at using massive parallelism to execute shaders blazingly fast.</p>
<div style="border-bottom: black 1px solid; border-left: black 1px solid; padding-bottom: 10px; background-color: #f0f0ff; margin-top: 20px; padding-left: 10px; padding-right: 10px; margin-bottom: 20px; margin-left: 10px; border-top: black 1px solid; border-right: black 1px solid; padding-top: 10px">
<p>One cool example of a PDE solver is a <a href="http://http.developer.nvidia.com/GPUGems3/gpugems3_ch30.html">liquid and smoke simulator</a>. The structure of the simulation is similar to my trivial heat dissipation example, but instead of tracking the temperature of each grid point, the smoke simulator tracks pressure and velocity. Just as in the heat dissipation example, a grid point is affected by all of its nearest neighbors in each iteration.</p>
<p>&#160;</p>
<p><object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/DER5xp29z6w&amp;hl=en_US&amp;fs=1&amp;rel=0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/DER5xp29z6w&amp;hl=en_US&amp;fs=1&amp;rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object></p>
<p>This simulation was developed by <a href="http://www.cs.caltech.edu/~keenan/">Keenan Crane</a>.</div>
<div style="border-bottom: black 1px solid; border-left: black 1px solid; padding-bottom: 10px; background-color: #f0f0ff; margin-top: 20px; padding-left: 10px; padding-right: 10px; margin-bottom: 20px; margin-left: 10px; border-top: black 1px solid; border-right: black 1px solid; padding-top: 10px">
<p>For a view into general computation on GPUs in 2004 when hacked-up pixel shaders were the state of the art, see the <a href="http://http.developer.nvidia.com/GPUGems2/gpugems2_part04.html">General-Purpose Computation on GPUs</a> section of GPU Gems 2.</p>
</div>
<h3>Arrival of GPGPU</h3>
<p>Once GPUs have shown themselves to be a good fit for certain types of high-performance computations (like PDEs), GPU manufacturers moved to make GPUs more attractive for general-purpose computing. The idea of General Purpose computation on a GPU (“GPGPU”) became a hot topic in high-performance computing.</p>
<p>GPGPU computing is based around <strong>compute kernels</strong>. A compute kernel is a generalization of a pixel shader:</p>
<ul>
<li>Like a pixel shader, a compute kernel is a routine that will be invoked on each point in the <strong>input space</strong>. </li>
<li>A pixel shader always operates on two-dimensional space. A compute kernel can work on space of <strong>any dimensionality</strong>. </li>
<li>A pixel shader returns a single color. A compute kernel can write an <strong>arbitrary number of outputs</strong>. </li>
<li>A pixel shader operates on 32-bit floating-point numbers. A compute kernel also supports <strong>64-bit floating-point</strong> numbers and <strong>integers</strong>. </li>
<li>A pixel shader reads from textures. A compute kernel can read from any place in <strong>GPU memory</strong>. </li>
<li>Additionally, compute kernels running on the same core can share data via an explicitly managed <strong>per-core cache</strong>. </li>
</ul>
<h3>Comparison of a GPU and a CPU</h3>
<p>The control flow of a modern application is typically very complicated. Just think about all the <strong>different tasks</strong> that must be completed to show this article in your browser. To display this blog article, the CPU has to communicate with various devices, maintain thousands of data structures, position thousands of UI elements, parse perhaps a hundred file formats, … that does not even begin to scratch the surface. And, not only are all of these tasks different, they also depend on each other in very complex ways.</p>
<p>Compare that with the control flow of a pixel shader. A pixel shader is a <strong>single routine</strong> that needs to be invoked roughly a million times, each time on a different input. Different shader invocations are pretty much independent and once all are done, the GPU starts over again with a scene where objects have moved a bit.</p>
<p>It shouldn’t come as a surprise that hardware optimized for running a pixel shader will be <strong>quite different</strong> from hardware optimized for tasks like viewing web pages. A CPU greatly benefits from a sophisticated execution pipeline with multi-level caches, instruction reordering, prefetching, branch prediction, and other clever optimizations. A GPU does not need most of those complex features for its much simpler control flow. Instead, a GPU benefits from lots of Arithmetic Logic Units (ALUs) to add, multiply and divide floating point numbers in parallel.</p>
<p>This table shows the most important differences between a CPU and a GPU today:</p>
<table style="text-align: left" border="1" cellspacing="0" cellpadding="2" width="541">
<tbody>
<tr>
<td valign="top" width="257"><strong>CPU</strong></td>
<td valign="top" width="282"><strong>GPU</strong></td>
</tr>
<tr>
<td valign="top" width="257"><strong>2-4</strong> cores</td>
<td valign="top" width="282"><strong>16-32</strong> cores</td>
</tr>
<tr>
<td valign="top" width="257">Each core runs <strong>1-2</strong> independent threads in parallel</td>
<td valign="top" width="282">Each core runs <strong>16-32</strong> threads in parallel. All threads on a core must execute the <strong>same instruction </strong>at any time.</td>
</tr>
<tr>
<td valign="top" width="257"><strong>Automatically managed </strong>hierarchy of caches</td>
<td valign="top" width="282">Each core has 16-64kB of cache, <strong>explicitly managed </strong>by the programmer</td>
</tr>
<tr>
<td valign="top" width="257">0.1 billion floating-point operations / second (<strong>0.1 TFLOP</strong>)</td>
<td valign="top" width="282">1 billion floating-point operations / second (<strong>1 TFLOP</strong>)</td>
</tr>
<tr>
<td valign="top" width="257">Main memory throughput: 10GB / sec</td>
<td valign="top" width="282">GPU memory throughput: 100GB / sec</td>
</tr>
</tbody>
</table>
<p>&#160;</p>
<p>All of this means that if a program can be broken up into many threads all doing the same thing on different data (ideally executing arithmetic operations), a GPU will probably be able to do this an order of magnitude faster than a CPU. On the other hand, on an application with a complex control flow, CPU is going to be the one winning by orders of magnitude. Going back to my earlier example, it should be clear why a CPU will excel at running a browser and a GPU will excel at executing a pixel shader.</p>
<p>This chart illustrates how a CPU and a GPU use up their “silicon budget”. A CPU uses most of its transistors for the L1 cache and for execution control. A GPU dedicates the bulk of its transistors to Arithmetic Logic Units (ALUs). </p>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://igoro.com/wordpress/wp-content/uploads/2010/03/image12.png" width="408" height="147" /> </p>
<p><font size="1">Adapted from </font><a href="http://developer.download.nvidia.com/compute/cuda/2_3/toolkit/docs/NVIDIA_CUDA_Programming_Guide_2.3.pdf"><font size="1">NVidia’s CUDA Programming Guide</font></a><font size="1">.</font></p>
<div style="border-bottom: black 1px solid; border-left: black 1px solid; padding-bottom: 10px; background-color: #f0f0ff; margin-top: 20px; padding-left: 10px; padding-right: 10px; margin-bottom: 20px; margin-left: 10px; border-top: black 1px solid; border-right: black 1px solid; padding-top: 10px">
<p>NVidia’s upcoming Fermi chip will slightly change the comparison table. Fermi introduces a per-core automatically-managed L1 cache. It will be very interesting to see what kind of impact the introduction of an L1 cache will have on the types of programs that can run on the GPU. One point is fairly clear – the penalty for register spills into main memory will be greatly reduced (this point may not make sense until you read the next section).</p>
</div>
<h3>GPGPU Programming</h3>
<p>Today, writing efficient GPGPU programs requires in-depth understanding of the hardware. There are three popular programming models:</p>
<ul>
<li>DirectCompute – Microsoft’s API for defining compute kernels, introduced in DirectX 11 </li>
<li>CUDA – NVidia’s C-based language for programming compute kernels </li>
<li>OpenCL – API originally proposed by Apple and now developed by Khronos Group </li>
</ul>
<p>Conceptually, the models are very similar. The table below summarizes some of the terminology differences between the models:</p>
<table border="1" cellspacing="0" cellpadding="2" width="379">
<tbody>
<tr>
<td valign="top" width="149"><strong>DirectCompute&#160; </strong></td>
<td valign="top" width="133"><strong>CUDA&#160; </strong></td>
<td valign="top" width="111"><strong>OpenCL</strong></td>
</tr>
<tr>
<td valign="top" width="149">thread</td>
<td valign="top" width="133">thread</td>
<td valign="top" width="111">work item</td>
</tr>
<tr>
<td valign="top" width="149">thread group</td>
<td valign="top" width="133">thread block</td>
<td valign="top" width="111">work group</td>
</tr>
<tr>
<td valign="top" width="149">group-shared memory</td>
<td valign="top" width="133">shared memory</td>
<td valign="top" width="111">local memory</td>
</tr>
<tr>
<td valign="top" width="149">warp?</td>
<td valign="top" width="133">warp</td>
<td valign="top" width="111">wavefront</td>
</tr>
<tr>
<td valign="top" width="149">barrier</td>
<td valign="top" width="133">barrier</td>
<td valign="top" width="111">barrier</td>
</tr>
</tbody>
</table>
<p>&#160;</p>
<p>Writing high-performance GPGPU code is not for the faint at heart (although the same could probably be said about any type of high-performance computing). Here are examples of some issues you need to watch out for when writing compute kernels:</p>
<ul>
<li>The program has to have <strong>plenty of threads</strong> (thousands) </li>
<li><strong>Not too many threads</strong>, though, or cores will run out of registers and will have to simulate additional registers using main GPU memory. </li>
<li>It is important that threads running on one core access main memory in such a pattern that the hardware will be <strong>coalesce</strong> <strong>the memory accesses </strong>from different threads. This optimization alone can make an order of magnitude difference. </li>
<li>… and so on. </li>
</ul>
<p>Explaining all of these performance topics in detail is well beyond the scope of this article, but hopefully this gives you an idea of what GPGPU programming is about, and what kinds of problems it can be applied to.</p>
<div style="border-bottom: black 1px solid; border-left: black 1px solid; padding-bottom: 10px; background-color: #f0f0ff; margin-top: 20px; padding-left: 10px; padding-right: 10px; margin-bottom: 20px; margin-left: 10px; border-top: black 1px solid; border-right: black 1px solid; padding-top: 10px">
<p>Read more of my articles:</p>
<p><a href="http://igoro.com/archive/gallery-of-processor-cache-effects/">Gallery of processor cache effects</a></p>
<p><a href="http://igoro.com/archive/what-really-happens-when-you-navigate-to-a-url/">What really happens when you navigate to a URL</a></p>
<p><a href="http://igoro.com/archive/human-heart-is-a-turing-machine-research-on-xbox-360-shows-wait-what/">Human heart is a Turing machine, research on XBox 360 shows. Wait, what?</a></p>
<p><a href="http://igoro.com/archive/skip-lists-are-fascinating/">Skip lists are fascinating!</a></p>
<p>And if you like my blog, <a href="http://igoro.com/feed/">subscribe</a>!</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://igoro.com/archive/how-gpu-came-to-be-used-for-general-computation/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>What really happens when you navigate to a URL</title>
		<link>http://igoro.com/archive/what-really-happens-when-you-navigate-to-a-url/</link>
		<comments>http://igoro.com/archive/what-really-happens-when-you-navigate-to-a-url/#comments</comments>
		<pubDate>Tue, 09 Feb 2010 08:14:26 +0000</pubDate>
		<dc:creator>Igor Ostrovsky</dc:creator>
				<category><![CDATA[Cool Stuff]]></category>

		<guid isPermaLink="false">http://igoro.com/?p=422</guid>
		<description><![CDATA[div.mynote { border: black 1px solid; padding: 10px; background-color: #f0f0ff; margin-top: 20px; margin-bottom: 20px; margin-left: 10px; > As a software developer, you certainly have a high-level picture of how web apps work and what kinds of technologies are involved: the browser, HTTP, HTML, web server, request handlers, and so on. In this article, we will [...]]]></description>
			<content:encoded><![CDATA[<style>div.mynote { border: black 1px solid; padding: 10px; background-color: #f0f0ff; margin-top: 20px; margin-bottom: 20px; margin-left: 10px; ></style>
<p>As a software developer, you certainly have a high-level picture of how web apps work and what kinds of technologies are involved: the browser, HTTP, HTML, web server, request handlers, and so on.</p>
<p>In this article, we will take a deeper look at the sequence of events that take place when you visit a URL.</p>
<h3>1. You enter a URL into the browser</h3>
<p>It all starts here:</p>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://igoro.com/wordpress/wp-content/uploads/2010/02/image4.png" width="591" height="103" /> </p>
<p><strong></strong></p>
<h3>2. The browser looks up the IP address for the domain name</h3>
<p>&#160;<img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://igoro.com/wordpress/wp-content/uploads/2010/02/image13.png" width="228" height="96" /> </p>
<p>The first step in the navigation is to figure out the IP address for the visited domain. The DNS lookup proceeds as follows:</p>
<p> <span id="more-422"></span>
<ul>
<li><strong>Browser cache – </strong>The browser caches DNS records for some time. Interestingly, the OS does not tell the browser the time-to-live for each DNS record, and so the browser caches them for a fixed duration (varies between browsers, 2 – 30 minutes). </li>
<li><strong>OS cache</strong> – If the browser cache does not contain the desired record, the browser makes a system call (gethostbyname in Windows). The OS has its own cache. </li>
<li><strong>Router cache</strong> – The request continues on to your router, which typically has its own DNS cache. </li>
<li><strong>ISP DNS cache</strong> – The next place checked is the cache ISP’s DNS server. With a cache, naturally. </li>
<li><strong>Recursive search</strong> – Your ISP’s DNS server begins a recursive search, from the root nameserver, through the .com top-level nameserver, to Facebook’s nameserver. Normally, the DNS server will have names of the .com nameservers in cache, and so a hit to the root nameserver will not be necessary. </li>
</ul>
<p>Here is a diagram of what a recursive DNS search looks like:</p>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="500px-An_example_of_theoretical_DNS_recursion_svg" border="0" alt="500px-An_example_of_theoretical_DNS_recursion_svg" src="http://igoro.com/wordpress/wp-content/uploads/2010/02/500pxAn_example_of_theoretical_DNS_recursion_svg.png" width="500" height="178" />&#160;</p>
<div class="mynote">
<p>One worrying thing about DNS is that the entire domain like wikipedia.org or facebook.com seems to map to a single IP address. Fortunately, there are ways of mitigating the bottleneck:</p>
<ul>
<li><strong>Round-robin DNS</strong> is a solution where the DNS lookup returns multiple IP addresses, rather than just one. For example, facebook.com actually maps to four IP addresses. </li>
<li><strong>Load-balancer</strong> is the piece of hardware that listens on a particular IP address and forwards the requests to other servers. Major sites will typically use expensive high-performance load balancers. </li>
<li><strong>Geographic DNS </strong>improves scalability by mapping a domain name to different IP addresses, depending on the client’s geographic location. This is great for hosting static content so that different servers don’t have to update shared state. </li>
<li><strong>Anycast</strong> is a routing technique where a single IP address maps to multiple physical servers. Unfortunately, anycast does not fit well with TCP and is rarely used in that scenario. </li>
</ul></div>
<div class="mynote">
<p>Most of the DNS servers themselves use anycast to achieve high availability and low latency <strong>of the DNS lookups</strong>.</p>
</p></div>
<h3>3. The browser sends a HTTP request to the web server</h3>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; margin-left: 0px; border-left-width: 0px; margin-right: 0px" title="image" border="0" alt="image" src="http://igoro.com/wordpress/wp-content/uploads/2010/02/image22.png" width="216" height="95" /> </p>
<p>You can be pretty sure that Facebook’s homepage will not be served from the browser cache because dynamic pages expire either very quickly or immediately (expiry date set to past).</p>
<p>So, the browser will send this request to the Facebook server:</p>
<pre class="code">GET http://facebook.com/ HTTP/1.1
Accept: application/x-ms-application, image/jpeg, application/xaml+xml, <font style="color: lightblue">[...]</font>
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; <font style="color: lightblue">[...]</font>
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
Host: facebook.com
Cookie: datr=1265876274-<font style="color: lightblue">[...]</font>; locale=en_US; lsd=WW<font style="color: lightblue">[...]</font>; c_user=2101<font style="color: lightblue">[...]</font></pre>
<p>The GET request names the <strong>URL</strong> to fetch<strong>:</strong> “http://facebook.com/”. The browser identifies itself (<strong>User-Agent</strong> header), and states what types of responses it will accept (<strong>Accept</strong> and <strong>Accept-Encoding</strong> headers). The <strong>Connection</strong> header asks the server to keep the TCP connection open for further requests.</p>
<p>The request also contains the <strong>cookies</strong> that the browser has for this domain. As you probably already know, cookies are key-value pairs that track the state of a web site in between different page requests. And so the cookies store the name of the logged-in user, a secret number that was assigned to the user by the server, some of user’s settings, etc. The cookies will be stored in a text file on the client, and sent to the server with every request.</p>
<div class="mynote">
<p>There is a variety of tools that let you view the raw HTTP requests and corresponding responses. My favorite tool for viewing the raw HTTP traffic is <a href="http://www.fiddler2.com/fiddler2/">fiddler</a>, but there are many other tools (e.g., FireBug) These tools are a great help when optimizing a site.</p>
</div>
<div class="mynote">
<p>In addition to GET requests, another type of requests that you may be familiar with is a POST request, typically used to submit forms. A GET request sends its parameters via the URL (e.g.: http://robozzle.com/puzzle.aspx<strong>?id=85</strong>). A POST request sends its parameters in the request body, just under the headers.</p>
</div>
<div class="mynote">
<p>The trailing slash in the URL “http://facebook.com/” is important. In this case, the browser can safely add the slash. For URLs of the form http://example.com/folderOrFile, the browser cannot automatically add a slash, because it is not clear whether folderOrFile is a folder or a file. In such cases, the browser will visit the URL without the slash, and the server will respond with a redirect, resulting in an unnecessary roundtrip.</p>
</div>
<h3>4. The facebook server responds with a permanent redirect</h3>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://igoro.com/wordpress/wp-content/uploads/2010/02/image8.png" width="214" height="87" /> </p>
<p>This is the response that the Facebook server sent back to the browser request:</p>
<pre class="code">HTTP/1.1 301 Moved Permanently
Cache-Control: private, no-store, no-cache, must-revalidate, post-check=0,
      pre-check=0
Expires: Sat, 01 Jan 2000 00:00:00 GMT
Location: http://www.facebook.com/
P3P: CP=&quot;DSP LAW&quot;
Pragma: no-cache
Set-Cookie: made_write_conn=deleted; expires=Thu, 12-Feb-2009 05:09:50 GMT;
      path=/; domain=.facebook.com; httponly
Content-Type: text/html; charset=utf-8
X-Cnection: close
Date: Fri, 12 Feb 2010 05:09:51 GMT
Content-Length: 0</pre>
<p>The server responded with a 301 Moved Permanently response to tell the browser to go to “http://www.facebook.com/” instead of “http://facebook.com/”. </p>
<div class="mynote">
<p>There are interesting reasons why the server insists on the redirect instead of immediately responding with the web page that the user wants to see.</p>
<p>One reason has to do with <strong>search engine rankings</strong>. See, if there are two URLs for the same page, say <a href="http://www.igoro.com/">http://www.igoro.com/</a> and <a href="http://igoro.com/">http://igoro.com/</a>, search engine may consider them to be two different sites, each with fewer incoming links and thus a lower ranking. Search engines understand permanent redirects (301), and will combine the incoming links from both sources into a single ranking.</p>
<p>Also, multiple URLs for the same content are not <strong>cache-friendly</strong>. When a piece of content has multiple names, it will potentially appear multiple times in caches.</p>
</div>
<h3>5. The browser follows the redirect</h3>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://igoro.com/wordpress/wp-content/uploads/2010/02/image23.png" width="216" height="95" /></p>
<p>The browser now knows that “http://www.facebook.com/” is the correct URL to go to, and so it sends out another GET request:</p>
<pre class="code">GET http://www.facebook.com/ HTTP/1.1
Accept: application/x-ms-application, image/jpeg, application/xaml+xml, <font style="color: lightblue">[...]</font>
Accept-Language: en-US
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; <font style="color: lightblue">[...]</font>
Accept-Encoding: gzip, deflate
Connection: Keep-Alive
Cookie: lsd=XW<font style="color: lightblue">[...]</font>; c_user=21<font style="color: lightblue">[...]</font>; x-referer=<font style="color: lightblue">[...]</font>
Host: www.facebook.com</pre>
<p>The meaning of the headers is the same as for the first request.</p>
<h3>6. The server ‘handles’ the request</h3>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://igoro.com/wordpress/wp-content/uploads/2010/02/image9.png" width="93" height="78" /> </p>
<p>The server will receive the GET request, process it, and send back a response.</p>
<p>This may seem like a straightforward task, but in fact there is a lot of interesting stuff that happens here – even on a simple site like my blog, let alone on a massively scalable site like facebook.</p>
<ul>
<li><strong>Web server software<br /></strong>The web server software (e.g., IIS or Apache) receives the HTTP request and decides which request handler should be executed to handle this request. A request handler is a program (in ASP.NET, PHP, Ruby, …) that reads the request and generates the HTML for the response.
<p>In the simplest case, the request handlers can be stored in a file hierarchy whose structure mirrors the URL structure, and so for example <a href="http://example.com/folder1/page1.aspx">http://example.com/folder1/page1.aspx</a> URL will map to file /httpdocs/folder1/page1.aspx. The web server software can also be configured so that URLs are manually mapped to request handlers, and so the public URL of page1.aspx could be <a href="http://example.com/folder1/page1">http://example.com/folder1/page1</a>. </p>
</li>
<li><strong>Request handler<br /></strong>The request handler reads the request, its parameters, and cookies. It will read and possibly update some data stored on the server. Then, the request handler will generate a HTML response. </li>
</ul>
<div class="mynote">
<p>One interesting difficulty that every dynamic website faces is how to store data. Smaller sites will often have a single SQL database to store their data, but sites that store a large amount of data and/or have many visitors have to find a way to split the database across multiple machines. Solutions include sharding (splitting up a table across multiple databases based on the primary key), replication, and usage of simplified databases with weakened consistency semantics. </p>
</div>
<div class="mynote">
<p>One technique to keep data updates cheap is to defer some of the work to a batch job. For example, Facebook has to update the newsfeed in a timely fashion, but the data backing the “People you may know” feature may only need to be updated nightly (my guess, I don’t actually know how they implement this feature). Batch job updates result in staleness of some less important data, but can make data updates much faster and simpler.</p>
</div>
<h3>7. The server sends back a HTML response</h3>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://igoro.com/wordpress/wp-content/uploads/2010/02/image10.png" width="214" height="87" /> </p>
<p>Here is the response that the server generated and sent back:</p>
<pre class="code">HTTP/1.1 200 OK
Cache-Control: private, no-store, no-cache, must-revalidate, post-check=0,
    pre-check=0
Expires: Sat, 01 Jan 2000 00:00:00 GMT
P3P: CP=&quot;DSP LAW&quot;
Pragma: no-cache
Content-Encoding: gzip
Content-Type: text/html; charset=utf-8
X-Cnection: close
Transfer-Encoding: chunked
Date: Fri, 12 Feb 2010 09:05:55 GMT

2b3��������T�n�@����<font style="color: lightblue">[...]</font></pre>
<p>The entire response is 36 kB, the bulk of them in the byte blob at the end that I trimmed.</p>
<p>The <strong>Content-Encoding</strong> header tells the browser that the response body is compressed using the gzip algorithm. After decompressing the blob, you’ll see the HTML you’d expect:</p>
<pre>&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Strict//EN&quot;&#160;&#160;&#160;
      &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd&quot;&gt;
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot; xml:lang=&quot;en&quot;
      lang=&quot;en&quot; id=&quot;facebook&quot; class=&quot; no_js&quot;&gt;
&lt;head&gt;
&lt;meta http-equiv=&quot;Content-type&quot; content=&quot;text/html; charset=utf-8&quot; /&gt;
&lt;meta http-equiv=&quot;Content-language&quot; content=&quot;en&quot; /&gt;
...</pre>
<p>In addition to compression, headers specify whether and how to cache the page, any cookies to set (none in this response), privacy information, etc.</p>
<div class="mynote">
<p>Notice the header that sets <strong>Content-Type</strong> to <strong>text/html</strong>. The header instructs the browser to render the response content as HTML, instead of say downloading it as a file. The browser will use the header to decide how to interpret the response, but will consider other factors as well, such as the extension of the URL.</p>
</div>
<h3>8. The browser begins rendering the HTML</h3>
<p>Even before the browser has received the entire HTML document, it begins rendering the website:</p>
<p>&#160;<img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://igoro.com/wordpress/wp-content/uploads/2010/02/image6.png" width="244" height="137" /> </p>
<h3>9. The browser sends requests for objects embedded in HTML</h3>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://igoro.com/wordpress/wp-content/uploads/2010/02/image11.png" width="214" height="126" /> </p>
<p>As the browser renders the HTML, it will notice tags that require fetching of other URLs. The browser will send a GET request to retrieve each of these files.</p>
<p>Here are a few URLs that my visit to facebook.com retrieved:</p>
<ul>
<li><strong>Images<br /></strong>http://static.ak.fbcdn.net/rsrc.php/z12E0/hash/8q2anwu7.gif<br />http://static.ak.fbcdn.net/rsrc.php/zBS5C/hash/7hwy7at6.gif<br />… </li>
<li><strong>CSS style sheets<br /></strong>http://static.ak.fbcdn.net/rsrc.php/z448Z/hash/2plh8s4n.css<br />http://static.ak.fbcdn.net/rsrc.php/zANE1/hash/cvtutcee.css<br />… </li>
<li><strong>JavaScript files</strong><br />http://static.ak.fbcdn.net/rsrc.php/zEMOA/hash/c8yzb6ub.js<br />http://static.ak.fbcdn.net/rsrc.php/z6R9L/hash/cq2lgbs8.js<br />…</li>
</ul>
<p>Each of these URLs will go through process a similar to what the HTML page went through. So, the browser will look up the domain name in DNS, send a request to the URL, follow redirects, etc.</p>
<p>However, static files &#8211; unlike dynamic pages &#8211; allow the browser to cache them. Some of the files may be served up from cache, without contacting the server at all. The browser knows how long to cache a particular file because the response that returned the file contained an Expires header. Additionally, each response may also contain an ETag header that works like a version number – if the browser sees an ETag for a version of the file it already has, it can stop the transfer immediately.</p>
<div class="mynote">
<p>Can you guess what <strong>“fbcdn.net”</strong> in the URLs stands for? A safe bet is that it means “Facebook content delivery network”. Facebook uses a content delivery network (CDN) to distribute static content – images, style sheets, and JavaScript files. So, the files will be copied to many machines across the globe.</p>
<p>Static content often represents the bulk of the bandwidth of a site, and can be easily replicated across a CDN. Often, sites will use a third-party CDN provider, instead of operating a CND themselves. For example, Facebook’s static files are hosted by Akamai, the largest CDN provider.</p>
<p>As a demonstration, when you try to ping static.ak.fbcdn.net, you will get a response from an akamai.net server. Also, interestingly, if you ping the URL a couple of times, may get responses from different servers, which demonstrates the load-balancing that happens behind the scenes.</p>
</div>
<h3>10. The browser sends further asynchronous (AJAX) requests</h3>
<p><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://igoro.com/wordpress/wp-content/uploads/2010/02/image12.png" width="214" height="120" /> </p>
<p>In the spirit of Web 2.0, the client continues to communicate with the server even after the page is rendered.</p>
<p>For example, Facebook chat will continue to update the list of your logged in friends as they come and go. To update the list of your logged-in friends, the JavaScript executing in your browser has to send an asynchronous request to the server. The asynchronous request is a programmatically constructed GET or POST request that goes to a special URL. In the Facebook example, the client sends a POST request to http://www.facebook.com/ajax/chat/buddy_list.php to fetch the list of your friends who are online.</p>
<p>This pattern is sometimes referred to as “AJAX”, which stands for “Asynchronous JavaScript And XML”, even though there is no particular reason why the server has to format the response as XML. For example, Facebook returns snippets of JavaScript code in response to asynchronous requests.</p>
<div class="mynote">
<p>Among other things, the fiddler tool lets you view the asynchronous requests sent by your browser. In fact, not only you can observe the requests passively, but you can also modify and resend them. The fact that it is this easy to “spoof” AJAX requests causes a lot of grief to developers of online games with scoreboards. (Obviously, please don’t cheat that way.)</p>
</div>
<div class="mynote">
<p>Facebook chat provides an example of an interesting problem with AJAX: pushing data from server to client. Since HTTP is a request-response protocol, the chat server cannot push new messages to the client. Instead, the client has to poll the server every few seconds to see if any new messages arrived.</p>
<p><a href="http://en.wikipedia.org/wiki/Push_technology#Long_polling">Long polling</a> is an interesting technique to decrease the load on the server in these types of scenarios. If the server does not have any new messages when polled, it simply does not send a response back. And, if a message for this client is received within the timeout period, the server will find the outstanding request and return the message with the response.</p>
</div>
<h3>Conclusion</h3>
<p>Hopefully this gives you a better idea of how the different web pieces work together.</p>
<div class="mynote">
<p>Read more of my articles:</p>
<p><a href="http://igoro.com/archive/gallery-of-processor-cache-effects/">Gallery of processor cache effects</a></p>
<p><a href="http://igoro.com/archive/human-heart-is-a-turing-machine-research-on-xbox-360-shows-wait-what/">Human heart is a Turing machine, research on XBox 360 shows. Wait, what?</a></p>
<p><a href="http://igoro.com/archive/self-printing-game-of-life-in-c/">Self-printing Game of Life in C#</a></p>
<p><a href="http://igoro.com/archive/skip-lists-are-fascinating/">Skip lists are fascinating!</a></p>
<p>And if you like my blog, <a href="http://igoro.com/feed/">subscribe</a>!</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://igoro.com/archive/what-really-happens-when-you-navigate-to-a-url/feed/</wfw:commentRss>
		<slash:comments>80</slash:comments>
		</item>
		<item>
		<title>Gallery of Processor Cache Effects</title>
		<link>http://igoro.com/archive/gallery-of-processor-cache-effects/</link>
		<comments>http://igoro.com/archive/gallery-of-processor-cache-effects/#comments</comments>
		<pubDate>Tue, 19 Jan 2010 10:28:11 +0000</pubDate>
		<dc:creator>Igor Ostrovsky</dc:creator>
				<category><![CDATA[Cool Stuff]]></category>

		<guid isPermaLink="false">http://igoro.com/?p=366</guid>
		<description><![CDATA[Most of my readers will understand that cache is a fast but small type of memory that stores recently accessed memory locations.  This description is reasonably accurate, but the &#8220;boring&#8221; details of how processor caches work can help a lot when trying to understand program performance. In this blog post, I will use code samples [...]]]></description>
			<content:encoded><![CDATA[<p>Most of my readers will understand that cache is a fast but small type of memory that stores recently accessed memory locations.  This description is reasonably accurate, but the &#8220;boring&#8221; details of how processor caches work can help a lot when trying to understand program performance.</p>
<p>In this blog post, I will use code samples to illustrate various aspects of how caches work, and what is the impact on the performance of real-world programs.</p>
<p>The examples are in C#, but the language choice has little impact on the performance scores and the conclusions they lead to.</p>
<h3>Example 1: Memory accesses and performance</h3>
<p>How much faster do you expect Loop 2 to run, compared Loop 1?</p>
<pre class="code"><span style="color: blue;">int</span>[] arr = <span style="color: blue;">new int</span>[64 * 1024 * 1024];
<span id="more-366"></span>
<span style="color: green;">// Loop 1</span>
<span style="color: blue;">for </span>(<span style="color: blue;">int </span>i = 0; i &lt; arr.Length; i++) arr[i] *= 3;

<span style="color: green;">// Loop 2</span>
<span style="color: blue;">for </span>(<span style="color: blue;">int </span>i = 0; i &lt; arr.Length; i += 16) arr[i] *= 3;</pre>
<p><!--More--></p>
<p>The first loop multiplies every value in the array by 3, and the second loop multiplies only every 16-th. The second loop only does about <strong>6% of the work</strong> of the first loop, but on modern machines, the two for-loops take about the same time<strong>:</strong> <strong>80</strong> and <strong>78</strong> <strong>ms</strong> respectively on my machine.</p>
<p>The reason why the loops take the same amount of time has to do with memory. The running time of these loops is dominated by the memory accesses to the array, not by the integer multiplications. And, as I’ll explain on Example 2, the hardware will perform the same main memory accesses for the two loops.</p>
<h3>Example 2: Impact of cache lines</h3>
<p>Let’s explore this example deeper. We will try other step values, not just 1 and 16:</p>
<pre class="code"><span style="color: blue;">for </span>(<span style="color: blue;">int </span>i = 0; i &lt; arr.Length; i += K) arr[i] *= 3;</pre>
<p>Here are the running times of this loop for different step values (K):</p>
<p><img style="display: inline; border-width: 0px;" title="image" src="http://igoro.com/wordpress/wp-content/uploads/2010/01/image6.png" border="0" alt="image" width="483" height="291" /></p>
<p>Notice that while step is in the range from 1 to 16, the running time of the for-loop hardly changes. But from 16 onwards, the running time is halved each time we double the step.</p>
<p>The reason behind this is that today’s CPUs do not access memory byte by byte. Instead, they fetch memory in chunks of (typically) 64 bytes, called <em>cache lines</em>. When you read a particular memory location, the entire cache line is fetched from the main memory into the cache. And, accessing other values from the same cache line is cheap!</p>
<p>Since 16 ints take up 64 bytes (one cache line), for-loops with a step between 1 and 16 have to touch the same number of cache lines: all of the cache lines in the array. But once the step is 32, we’ll only touch roughly every other cache line, and once it is 64, only every fourth.</p>
<p>Understanding of cache lines can be important for certain types of program optimizations. For example, alignment of data may determine whether an operation touches one or two cache lines. As we saw in the example above, this can easily mean that in the misaligned case, the operation will be twice slower.</p>
<h3>Example 3: L1 and L2 cache sizes</h3>
<p>Today’s computers come with two or three levels of caches, usually called L1, L2 and possibly L3. If you want to know the sizes of the different caches, you can use the <a href="http://technet.microsoft.com/en-us/sysinternals/cc835722.aspx">CoreInfo</a> SysInternals tool, or use the <a href="http://msdn.microsoft.com/en-us/library/ms683194(VS.85).aspx">GetLogicalProcessorInfo</a> Windows API call. Both methods will also tell you the cache line sizes, in addition to the cache sizes.</p>
<p>On my machine, CoreInfo reports that I have a 32kB L1 data cache, a 32kB L1 instruction cache, and a 4MB L2 data cache. The L1 caches are per-core, and the L2 caches are shared between pairs of cores:</p>
<pre class="code">Logical Processor to Cache Map:
*---  Data Cache          0, Level 1,   32 KB, Assoc   8, LineSize  64
*---  Instruction Cache   0, Level 1,   32 KB, Assoc   8, LineSize  64
-*--  Data Cache          1, Level 1,   32 KB, Assoc   8, LineSize  64
-*--  Instruction Cache   1, Level 1,   32 KB, Assoc   8, LineSize  64
**--  Unified Cache       0, Level 2,    4 MB, Assoc  16, LineSize  64
--*-  Data Cache          2, Level 1,   32 KB, Assoc   8, LineSize  64
--*-  Instruction Cache   2, Level 1,   32 KB, Assoc   8, LineSize  64
---*  Data Cache          3, Level 1,   32 KB, Assoc   8, LineSize  64
---*  Instruction Cache   3, Level 1,   32 KB, Assoc   8, LineSize  64
--**  Unified Cache       1, Level 2,    4 MB, Assoc  16, LineSize  64</pre>
<p>Let’s verify these numbers by an experiment. To do that, we’ll step over an array incrementing every 16th integer – a cheap way to modify every cache line. When we reach the last value, we loop back to the beginning. We’ll experiment with different array sizes, and we should see drops in the performance at the array sizes where the array spills out of one cache level.</p>
<p>Here is the program:</p>
<pre class="code"><span style="color: blue;">int </span>steps = 64 * 1024 * 1024; <span style="color: green;">// Arbitrary number of steps</span>
<span style="color: blue;">int </span>lengthMod = arr.Length - 1;
<span style="color: blue;">for </span>(<span style="color: blue;">int </span>i = 0; i &lt; steps; i++)
{
    arr[(i * 16) &amp; lengthMod]++; <span style="color: green;">// (x &amp; lengthMod) is equal to (x % arr.Length)
</span>}</pre>
<p>And here are the timings:</p>
<p> <img style="display: inline; border-width: 0px;" title="image" src="http://igoro.com/wordpress/wp-content/uploads/2010/02/image.png" border="0" alt="image" width="483" height="291" /></p>
<p>You can see distinct drops after 32kB and 4MB – the sizes of L1 and L2 caches on my machine.</p>
<h3>Example 4: Instruction-level parallelism</h3>
<p>Now, let’s take a look at something different. Out of these two loops, which one would you expect to be faster?</p>
<pre class="code"><span style="color: blue;">int </span>steps = 256 * 1024 * 1024;
<span style="color: blue;">int</span>[] a = <span style="color: blue;">new int</span>[2];

<span style="color: green;">// Loop 1
</span><span style="color: blue;">for </span>(<span style="color: blue;">int </span>i=0; i&lt;steps; i++) { a[0]++; a[0]++; }

<span style="color: green;">// Loop 2
</span><span style="color: blue;">for </span>(<span style="color: blue;">int </span>i=0; i&lt;steps; i++) { a[0]++; a[1]++; }</pre>
<p>It turns out that the second loop is about twice faster than the first loop, at least on all of the machines I tested. Why? This has to do with the dependencies between operations in the two loop bodies.</p>
<p>In the body of the first loop, operations depend on each other as follows:</p>
<p><img style="display: inline; border-width: 0px;" title="image" src="http://igoro.com/wordpress/wp-content/uploads/2010/01/image.png" border="0" alt="image" width="613" height="25" /></p>
<p>But in the second example, we only have these dependencies:</p>
<p><img style="display: inline; border-width: 0px;" title="image" src="http://igoro.com/wordpress/wp-content/uploads/2010/02/image2.png" border="0" alt="image" width="289" height="73" /></p>
<p>The modern processor has various parts that have a little bit of parallelism in them: it can access two memory locations in L1 at the same time, or perform two simple arithmetic operations. In the first loop, the processor cannot exploit this instruction-level parallelism, but in the second loop, it can.</p>
<p><strong>[UPDATE]</strong>: Many people on reddit are asking about compiler optimizations, and whether { a[0]++; a[0]++; } would just get optimized to { a[0]+=2; }. In fact, the C# compiler and CLR JIT will not do this optimization – not when array accesses are involved. I built all of the tests in release mode (i.e. with optimizations), but I looked at the JIT-ted assembly to verify that optimizations aren’t skewing the results.</p>
<h3>Example 5: Cache associativity</h3>
<p>One key decision in cache design is whether each chunk of main memory can be stored in any cache slot, or in just some of them.</p>
<p>There are three possible approaches to mapping cache slots to memory chunks:</p>
<ol>
<li><strong>Direct mapped cache</strong>
<p>Each memory chunk can only be stored only in one particular slot in the cache. One simple solution is to map the chunk with index chunk_index to cache slot (chunk_index % cache_slots). Two memory chunks that map to the same slot cannot be stored simultaneously in the cache.</li>
<li><strong>N-way set associative cache</strong>
<p>Each memory chunk can be stored in any one of N particular slots in the cache. As an example, in a 16-way cache, each memory chunk can be stored in 16 different cache slots. Commonly, chunks with indices with the same lowest order bits will all share 16 slots.</li>
<li><strong>Fully associative cache</strong>
<p>Each memory chunk can be stored in any slot in the cache. Effectively, the cache operates like a hash table.</li>
</ol>
<p>Direct mapped caches can suffer from conflicts &#8211; when multiple values compete for the same slot in the cache, they keep evicting each other out, and the hit rate plummets. On the other hand, fully associative caches are complicated and costly to implement in the hardware. N-way set associative caches are the typical solution for processor caches, as they make a good trade off between implementation simplicity and good hit rate.</p>
<p>For example, the 4MB L2 cache on my machine is 16-way associative. All 64-byte memory chunks are partitioned into sets (based on the lowest order bits of the chunk index), and chunks in the same set compete for 16 slots in the L2 cache.</p>
<p>Since the L2 cache has 65,536 slots, and each set will need 16 slots in the cache, we will have 4,096 sets. So, the lowest 12 bits of the chunk index will determine which set the chunk belongs to (2<sup>12</sup> = 4,096). As a result, cache lines at addresses that differ by a multiple of 262,144 bytes (4096 * 64) will compete for the same slot in the cache. The cache on my machine can hold at most 16 such cache lines.</p>
<p>In order for the effects of cache associativity to become apparent, I need to repeatedly access more than  16 elements from the same set. I will demonstrate this using the following method:</p>
<pre class="code"><span style="color: blue;">public static long </span>UpdateEveryKthByte(<span style="color: blue;">byte</span>[] arr, <span style="color: blue;">int </span>K)
{
    <span style="color: #2b91af;">Stopwatch </span>sw = <span style="color: #2b91af;">Stopwatch</span>.StartNew();
    <span style="color: blue;">const int </span>rep = 1024*1024; <span style="color: green;">// Number of iterations – arbitrary</span>

<span style="color: green;">    </span><span style="color: blue;">int </span>p = 0;
    <span style="color: blue;">for </span>(<span style="color: blue;">int </span>i = 0; i &lt; rep; i++)
    {
        arr[p]++;
        p += K;
        <span style="color: blue;">if </span>(p &gt;= arr.Length) p = 0;
    }

    sw.Stop();
    <span style="color: blue;">return </span>sw.ElapsedMilliseconds;
}</pre>
<p>This method increments every K-th value in the array. Once the it reaches the end of the array, it starts again from the beginning. After running sufficiently long (2^20 steps), the loop stops.</p>
<p>I ran UpdateEveryKthByte() with different array sizes (in 1MB increments) and different step sizes. Here is a plot of the results, with blue representing long running time, and white representing short:</p>
<p> <a href="http://igoro.com/wordpress/wp-content/uploads/2010/02/image3.png"><img style="display: inline; border-width: 0px;" title="image" src="http://igoro.com/wordpress/wp-content/uploads/2010/02/image_thumb1_opt.png" border="0" alt="image" width="582" height="299" /></a></p>
<p>The blue areas (long running times) are cases where the updated values <strong>could not be simultaneously held in the cache</strong> as we repeatedly iterated over them. The bright blue areas correspond to running times of ~80 ms, and the nearly white areas to ~10 ms.</p>
<p>Let’s explain the blue parts of the chart:</p>
<ol>
<li><strong>Why the vertical lines?</strong>The vertical lines show the step values that touch too many memory locations (&gt;16) from the same set. For those steps, we cannot simultaneously hold all touched values in the 16-way associative cache on my machine.
<p>Some bad step values are powers of two: 256 and 512. As an example, consider step 512 on an 8MB array. An 8MB cache line contains 32 values that are spaced by 262,144 bytes apart. All of those values will be updated by each pass of our loop, because 512 divides 262,144.</p>
<p>And since 32 &gt; 16, those 32 values will keep competing for the same 16 slots in the cache.</p>
<p>Some values that are not powers of two are simply unfortunate, and will end up visiting disproportionately many values from the same set. Those step values will also show up as as blue lines.</li>
<li><strong>Why do the vertical lines stop at 4MB array length?</strong>On arrays of 4MB or less, a 16-way associative cache is just as good as a fully associative one.
<p>A 16-way associative cache can hold at most 16 cache lines that are a multiple of 262,144 bytes apart. There is <strong>no set</strong> of 17 or more cache lines all aligned on 262,144-byte boundaries within 4MB, because 16 * 262,144 = 4,194,304.</li>
<li><strong>Why the blue triangle in upper left?</strong>In the triangle area, we cannot hold all necessary data in cache simultaneously … not due to the associativity, but simply because of the L2 cache size limit.
<p>For example, consider the array length 16MB with step 128. We are repeatedly updating every 128th byte in the array, which means that we touch every other 64-byte memory chunk. To store every other cache line of a 16MB array, we’d need 8MB cache. But, my machine only has 4MB of cache.</p>
<p>Even if the 4MB cache on my machine was fully associative, it still wouldn’t be able to hold 8MB of data.</li>
<li><strong>Why does the triangle fade out in the left?</strong>Notice that the gradient goes from 0 to 64 bytes – one cache line! As explained in examples 1 and 2, additional accesses to same cache line are nearly free. For example, when stepping by 16 bytes, it will take 4 steps to get to the next cache line. So, we get four memory accesses for the price of one.
<p>Since the number of steps is the same for all cases, a cheaper step results in a shorter running time.</li>
</ol>
<p>These patterns continue to hold as you extend the chart:</p>
<p><a href="http://igoro.com/wordpress/wp-content/uploads/2010/02/assoc_big1.png"><img style="display: inline; border-width: 0px;" title="assoc_big" src="http://igoro.com/wordpress/wp-content/uploads/2010/02/assoc_big_thumb1_opt.png" border="0" alt="assoc_big" width="582" height="299" /></a></p>
<p>Cache associativity is interesting to understand and can certainly be demonstrated, but it tends to be less of a problem compared to the other issues discussed in this article. It is certainly not something that should be at the forefront of your mind as you write programs.</p>
<h3>Example 6: False cache line sharing</h3>
<p>On multi-core machines, caches encounter another problem – consistency. Different cores have fully or partly separate caches. On my machine, L1 caches are separate (as is common), and there are two pairs of processors, each pair sharing an L2 cache. While the details vary, a modern multi-core machine will have a multi-level cache hierarchy, where the faster and smaller caches belong to individual processors.</p>
<p>When one processor modifies a value in its cache, other processors cannot use the old value anymore. That memory location will be invalidated in all of the caches. Furthermore, since caches operate on the granularity of cache lines and not individual bytes, the <strong>entire cache line</strong> will be invalidated in all caches!</p>
<p>To demonstrate this issue, consider this example:</p>
<pre class="code"><span style="color: blue;">private static int</span>[] s_counter = <span style="color: blue;">new int</span>[1024];
<span style="color: blue;">private void </span>UpdateCounter(<span style="color: blue;">int </span>position)
{
    <span style="color: blue;">for </span>(<span style="color: blue;">int </span>j = 0; j &lt; 100000000; j++)
    {
        s_counter[position] = s_counter[position] + 3;
    }
}</pre>
<p>On my quad-core machine, if I call UpdateCounter with parameters 0,1,2,3 from four different threads, it will take <strong>4.3 seconds </strong>until all threads are done.</p>
<p>On the other hand, if I call UpdateCounter with parameters 16,32,48,64 the operation will be done in <strong>0.28 seconds</strong>!</p>
<p>Why? In the first case, all four values are very likely to end up on the same cache line. Each time a core increments the counter, it invalidates the cache line that holds all four counters. All other cores will suffer a cache miss the next time they access their own counters. This kind of thread behavior effectively disables caches, <strong>crippling</strong> the program’s performance.</p>
<h3>Example 7: Hardware complexities</h3>
<p>Even when you know the basics of how caches work, the hardware will still sometimes surprise you. Different processors differ in optimizations, heuristics, and subtle details of how they do things.</p>
<p>On some processors, L1 cache can process two accesses in parallel if they access cache lines from different banks, and serially if they belong to the same bank. Also, processors can surprise you with clever optimizations. For example, the false-sharing example that I’ve used on several machines in the past did not work well on my machine without tweaks – my home machine can optimize the execution in the simplest cases to reduce the cache invalidations.</p>
<p>Here is one odd example of “hardware weirdness”:</p>
<pre class="code"><span style="color: blue;">private static int </span>A, B, C, D, E, F, G;
<span style="color: blue;">private static void </span>Weirdness()
{
    <span style="color: blue;">for </span>(<span style="color: blue;">int </span>i = 0; i &lt; 200000000; i++)
    {
        &lt;something&gt;
    }
}</pre>
<p>When I substitute three different blocks for “&lt;something&gt;”, I get these timings:</p>
<table border="0" cellspacing="0" cellpadding="2" width="362">
<tbody>
<tr>
<td width="199" valign="top"><strong>&lt;something&gt;</strong></td>
<td width="161" valign="top"><strong>Time</strong></td>
</tr>
<tr>
<td width="220" valign="top">A++; B++; C++; D++;</td>
<td width="169" valign="top">719 ms</td>
</tr>
<tr>
<td width="225" valign="top">A++; C++; E++; G++;</td>
<td width="172" valign="top">448 ms</td>
</tr>
<tr>
<td width="225" valign="top">A++; C++;</td>
<td width="174" valign="top">518 ms</td>
</tr>
</tbody>
</table>
<p>Incrementing fields A,B,C,D takes longer than incrementing fields A,C,E,G. And what’s even weirder, incrementing just A and C takes <strong>longer </strong>than increment A and C <strong>and</strong> E and G!</p>
<p>I don’t know for sure what is the reason behind these numbers, but I suspect it is related to memory banks. If someone can explain these numbers, I’d be very curious to hear about it.</p>
<p>The lesson of this example is that can be difficult to fully predict hardware performance. There is a lot that you <strong>can</strong> predict, but ultimately, it is very important to measure and verify your assumptions.</p>
<div style="background-color: #f6f6ff; margin-top: 20px; width: 600px; margin-bottom: 20px; margin-left: 10px; border: black 1px solid; padding: 4px;">
<p>Read more of my articles:</p>
<p><a href="http://igoro.com/archive/human-heart-is-a-turing-machine-research-on-xbox-360-shows-wait-what/">Human heart is a Turing machine, research on XBox 360 shows. Wait, what?</a></p>
<p><a href="http://igoro.com/archive/self-printing-game-of-life-in-c/">Self-printing Game of Life in C#</a></p>
<p><a href="http://igoro.com/archive/efficient-auto-complete-with-a-ternary-search-tree/">Efficient auto-complete with a ternary search tree</a></p>
<p><a href="http://igoro.com/archive/numbers-that-cannot-be-computed/">Numbers that cannot be computed</a></p>
<p>And if you like my blog, <a href="http://igoro.com/feed/">subscribe</a>!</p>
</div>
<h3>Conclusion</h3>
<p>Hopefully all of this helps you understand how caches work, and apply that knowledge when tuning your programs.</p>
]]></content:encoded>
			<wfw:commentRss>http://igoro.com/archive/gallery-of-processor-cache-effects/feed/</wfw:commentRss>
		<slash:comments>62</slash:comments>
		</item>
		<item>
		<title>Human heart is a Turing machine, research on XBox 360 shows. Wait, what?</title>
		<link>http://igoro.com/archive/human-heart-is-a-turing-machine-research-on-xbox-360-shows-wait-what/</link>
		<comments>http://igoro.com/archive/human-heart-is-a-turing-machine-research-on-xbox-360-shows-wait-what/#comments</comments>
		<pubDate>Thu, 24 Sep 2009 08:13:31 +0000</pubDate>
		<dc:creator>Igor Ostrovsky</dc:creator>
				<category><![CDATA[Cool Stuff]]></category>

		<guid isPermaLink="false">http://igoro.com/?p=285</guid>
		<description><![CDATA[Did you ever see one of those auto-generated random “academic papers” like this one? When I first saw the following title, my first thought was that it is a randomly-generated “paper”: Implications of the Turing completeness of reaction-diffusion models, informed by GPGPU simulations on an XBox 360: Cardiac arrhythmias, re-entry and the Halting problem [PDF] [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://commons.wikimedia.org/wiki/File:CoeurHumain.svg"><img style="margin: 0px 0px 10px 10px; display: inline; border: 0px;" title="211px-CoeurHumain_svg" src="http://robozzle.com/igoro/211px-CoeurHumain_svg.gif" border="0" alt="211px-CoeurHumain_svg" width="150" align="right" /></a>Did you ever see one of those auto-generated random “academic papers” like <a href="http://pdos.csail.mit.edu/scigen/rooter.pdf">this one</a>? When I first saw the following title, my first thought was that it is a randomly-generated “paper”:</p>
<p><a href="http://www.sciencedirect.com/science?_ob=ArticleURL&amp;_udi=B73G2-4WH2KVG-1&amp;_user=10&amp;_rdoc=1&amp;_fmt=&amp;_orig=search&amp;_sort=d&amp;_docanchor=&amp;view=c&amp;_searchStrId=1022400504&amp;_rerunOrigin=scholar.google&amp;_acct=C000050221&amp;_version=1&amp;_urlVersion=0&amp;_userid=10&amp;md5=979bc3e20f7e915c6cb32be391bc370d">Implications of the Turing completeness of reaction-diffusion models, informed by GPGPU simulations on an XBox 360: Cardiac arrhythmias, re-entry and the Halting problem</a> [<a href="http://research.microsoft.com/pubs/79271/turing.pdf">PDF</a>]</p>
<p>Turing completeness, cardiac arrhythmias, XBox 360… those things don’t seem to have much in common. But, I had my interest piqued. I looked up the paper and read through it. And, it turns out that not only is the paper serious, what it has to say is also quite interesting.</p>
<p><span id="more-285"></span></p>
<h3>Heart and logic circuits</h3>
<p>I had to take author’s word on the medical aspects of the article, since I know nothing about cardiology. Apparently, understanding of electrical signals between cells in a human heart is important for research into heart arrhythmias. Makes sense.</p>
<p>The important insight of the article is that a logic NOR gate can be simulated using electrical signals between heart cells. Constructing a NOR gate is a powerful result, because similarly to NAND, NOR is a universal logic gate. That means that all other logic gates like AND, OR and NOT can be built out of NORs:</p>
<p><span style="font-family: Courier New;"><span style="color: #0080ff;">NOT</span>(A)    = <span style="color: #0080ff;">NOR</span>(A, A)<br />
<span style="color: #0080ff;">OR</span>(A, B)  = <span style="color: #0080ff;">NOR</span>(<span style="color: #0080ff;">NOR</span>(A, B), <span style="color: #0080ff;">NOR</span>(A, B))<br />
<span style="color: #0080ff;">AND</span>(A, B) = </span><span style="font-family: Courier New;"><span style="color: #0080ff;">NOR</span>(<span style="color: #0080ff;">NOR</span>(A, A), <span style="color: #0080ff;">NOR</span>(B, B))</span></p>
<p>So, since you can simulate a NOR gate using cardiac cells, you can simulate an arbitrary logic circuit in heart tissue.</p>
<h3>Heart and Turing machines</h3>
<p>But, there has to be more to the story. The paper title mentioned Turing machines, and logic circuits are not Turing-complete. Halting problem doesn’t even make sense when applied to boolean expressions!</p>
<p>The missing part is the passage of time. See, a logic circuit is not Turing-complete. But, if you take a logic circuit with multiple inputs, the same number of outputs as inputs, and repeatedly apply the circuit over the results of the previous iteration, you get a Turing-complete system. This type of a system can be modeled with behavior of a heart tissue over a period of time.</p>
<p>The most intuitive explanation that I can think of is via <a href="http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life">Game of Life</a>. In the Game of Life, each cell dies, becomes alive or stays alive depending on how many live neighbors it had in the previous generation.  Here is one example of a Game of Life board in action:</p>
<p><a href="http://en.wikipedia.org/wiki/File:Gospers_glider_gun.gif"><img style="display: inline;" title="Gospers_glider_gun" src="http://robozzle.com/igoro/Gospers_glider_gun.gif" alt="Gospers_glider_gun" width="250" height="180" /></a> </p>
<p>Now, the important observation is that the Game of Life rules can be encoded using a logic circuit. For example, if the eight neighbors of a particular cell are represented as A, B … H, then the rule that the cell becomes alive if it has exactly three neighbors can be encoded as  ((A and B and C and not(D) and … and not(H)) or (A and B and not(C) and D and not(E) … and not(H)) or …). This expression will be combined with an OR together with the situations under which the cell remains alive, rather than becoming alive. This will be a pretty ugly logic circuit, but it should be clear that it can be constructed.</p>
<p>Since Game of Life is known to be Turing-complete, then an “iterated logic circuit” is also Turing-complete, and the behavior of cardiac tissue is … Turing-complete.</p>
<div style="border: black 1px solid; padding-bottom: 4px; background-color: #f6f6ff; padding-left: 4px; width: 600px; padding-right: 4px; margin-left: 10px;padding-top: 4px">Also read about <a href="http://igoro.com/archive/numbers-that-cannot-be-computed/">Numbers that cannot be computed</a> and&nbsp; <a title="Link to Self-printing Game of Life in C#" href="http://igoro.com/archive/self-printing-game-of-life-in-c/">Self-printing Game of Life in C#</a>.</div>
<h3>Why is this useful?</h3>
<p>Proving that a particular behavior of cardiac tissue is Turing-complete is a useful result because it shows that the cardiac tissue is in a certain sense “unpredictable”.</p>
<p>For example, since Game of Life is Turing-complete, the Halting problem applies. So, it is a proven fact that there is no general algorithm that can look at a particular Game of Life board and decide whether the movement will eventually stop or continue forever.</p>
<p>Similarly, there is no algorithm that can decide any of these properties for all Game-of-Life boards:</p>
<ul>
<li>Whether the board will ever reach a particular configuration</li>
<li>Whether the number of live cells will ever exceed X</li>
<li>Whether the game will ever enter a cycle</li>
<li>etc.</li>
</ul>
<p>Since the studied behavior of cardiac tissue is also Turing-complete, there is no general algorithm that can look at the state of cardiac tissue and decide whether the activity will ever stop, enter a regular pattern, achieve a particular configuration, etc. That is certainly a worthwhile result!</p>
<h3>What about the XBox?</h3>
<p><a href="http://commons.wikimedia.org/wiki/File:Xbox_360.jpg"><img style="margin: 0px 0px 10px 10px; display: inline; border: 0px;" title="367px-Xbox_360" src="http://robozzle.com/igoro/367pxXbox_360.jpg" border="0" alt="367px-Xbox_360" width="147" height="240" align="right" /></a>Constructing a NOR gate out of cardiac cells is computationally intensive, and the researcher used a GPU in an XBox 360 for that task.</p>
<p>However, the paper doesn’t conclusively show that using an XBox was a real benefit. The paper says that a C++ implementation that was originally “designed more for ease of expansion […] than for speed” ran slower on an XBox 360 CPU than an “unoptimized” shader-based implementation on an XBox 360 GPU. Comparing implementations not designed for speed is unconvincing. If the goal was to speed up the computation, why not first try to optimize the original code instead of porting it to shaders, which is undoubtedly a much more difficult task?</p>
<p>Also, the article doesn’t say how did XBox 360 CPU compare against an ordinary x86 machine, or against say a CUDA-based implementation on a common NVidia card. So, the paper doesn’t come close to showing that the researchers gained much by coding against the XBox 360 GPU, rather than following the current state-of-the-art approaches.</p>
<p>But, it is still a cool paper, and adding XBox 360 into the picture certainly attracted attention. The paper was reported in press, with titles such as these:</p>
<ul>
<li><a href="http://www.time.com/time/health/article/0,8599,1925332,00.html">How Xbox Can Help Fight Heart Disease</a> [time.com].</li>
<li><a href="http://www.techshout.com/science/2009/16/study-parallel-processor-computing-of-xbox-chip-could-save-thousands/">Parallel processor computing of XBox chip could save thousands</a> [techshout.com].</li>
</ul>
<p>And, if it weren’t for the sensational articles, I wouldn’t have found out about the paper at all, so I guess I shouldn’t complain.</p>
]]></content:encoded>
			<wfw:commentRss>http://igoro.com/archive/human-heart-is-a-turing-machine-research-on-xbox-360-shows-wait-what/feed/</wfw:commentRss>
		<slash:comments>26</slash:comments>
		</item>
		<item>
		<title>How to write a self-printing program</title>
		<link>http://igoro.com/archive/how-to-write-a-self-printing-program/</link>
		<comments>http://igoro.com/archive/how-to-write-a-self-printing-program/#comments</comments>
		<pubDate>Fri, 31 Oct 2008 16:46:38 +0000</pubDate>
		<dc:creator>Igor Ostrovsky</dc:creator>
				<category><![CDATA[Cool Stuff]]></category>
		<category><![CDATA[Cool]]></category>

		<guid isPermaLink="false">http://igoro.com/archive/how-to-write-a-self-printing-program/</guid>
		<description><![CDATA[As promised at the end of my recent post, I am going to explain how to implement a program that prints itself, in addition to doing other things (like playing Game of Life). A self-printing program &#8211; also called a quine &#8211; is a program that prints out its own source code. I will describe [...]]]></description>
			<content:encoded><![CDATA[<p>As promised at the end of my recent <a href="http://igoro.com/archive/self-printing-game-of-life-in-c">post</a>, I am going to explain how to implement a program that prints itself, in addition to doing other things (like playing Game of Life).</p>
<p>A self-printing program &#8211; also called a quine &#8211; is a program that prints out its own source code. I will describe one simple way to implement a quine that can be adapted to just about any programming language. The technique does not depend on any unusual language features, but also does not necessarily yield the shortest possible quine in a particular language.</p>
<p>The main idea behind this quine implementation is simple. The quine will consist of two parts: a definition of a string and the program core. The string will contain the source code of the program core. And, what will the program core do? It will print the string twice: once to print the string definition, and again to print the program core.</p>
</p>
<p><span id="more-83"></span>
</p>
<p>That&#8217;s pretty much all we need to do, except for some details. When printing the string the first time, we need to escape special characters and surround each line with quotes. Also, some code may need to come before the string definition (the &#8220;header&#8221;), and some may need to come after the program core (the &#8220;footer&#8221;). Fortunately, we can stuff all the code we need into the program core, so handling these details is not a big problem.</p>
<p>Let&#8217;s walk through a quine construction in C#. The quine will look like this:</p>
<pre class="code"><span style="color: blue">    using </span>System;
<span style="color: blue"></span><span style="color: blue">    class </span><span style="color: #2b91af">P </span>{
        <span style="color: blue">static void </span>Main() {
            <span style="color: blue">string</span>[] S = {
                <span style="color: green">// the program core, as a string array
            </span>};

            <span style="color: green">// the program core, as source code:<span style="color: green">            //     1. Print the program header</span>
            //     2. Print S, formatted as the definition of S
            //     3. Print S, formatted as source code            //     4. Print the program footer</span><span style="color: green">
        </span>}
    }</pre>
<p>Let&#8217;s implement the program core. That&#8217;s easy:</p>
<p><a href="http://11011.net/software/vspaste"></a></p>
<pre class="code"><span style="color: blue">    using </span>System;
<span style="color: blue">    class </span><span style="color: #2b91af">P </span>{
        <span style="color: blue">static void </span>Main() {
            <span style="color: blue">string</span>[] S = {
                <span style="color: green">// <span style="color: green">the program core, represented as a string array </span></span>
            };
            <span style="color: green">// 1. Print the program header
            </span><span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"using System;"</span>);
            <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"class P {"</span>);
            <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"    static void Main() {"</span>);

            <span style="color: green">// 2. Print S, formatted as the definition of S
            </span><span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"        string[] S = {"</span>);
            <span style="color: blue">foreach </span>(<span style="color: blue">string </span>line <span style="color: blue">in </span>S)
            {
                <span style="color: blue">string </span>escapedLine = line.Replace(<span style="color: #a31515">@"\"</span>, <span style="color: #a31515">@"\\"</span>).Replace(<span style="color: #a31515">"\""</span>, <span style="color: #a31515">"\\\""</span>);
                <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"\"{0}\","</span>, escapedLine);
            }
            <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"        };"</span>);

            <span style="color: green">// 3. Print S, formatted as source code
            </span><span style="color: blue">foreach </span>(<span style="color: blue">string </span>line <span style="color: blue">in </span>S) <span style="color: #2b91af">Console</span>.WriteLine(line);

            <span style="color: green">// 4. Print the program footer
            </span><span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"    }"</span>);
            <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"}"</span>);
        }
    }</pre>
<p>We also need to initialize string S. To do that, simply copy &amp; paste the program core source code into the definition of S, add a backslash before each occurrence of &#8221; or \, and surround each line with quotes.</p>
<p>Here is the final quine:</p>
<pre class="code"><span style="color: blue">using </span>System;
<span style="color: blue">class </span><span style="color: #2b91af">P
</span>{
    <span style="color: blue">static void </span>Main()
    {
        <span style="color: blue">string</span>[] S = {
<span style="color: #a31515">"        Console.WriteLine(\"using System;\");"</span>,
<span style="color: #a31515">"        Console.WriteLine(\"class P {\");"</span>,
<span style="color: #a31515">"        Console.WriteLine(\"    static void Main() {\");"</span>,
<span style="color: #a31515">""</span>,
<span style="color: #a31515">"        Console.WriteLine(\"        string[] S = {\");"</span>,
<span style="color: #a31515">"        foreach (string line in S) {"</span>,
<span style="color: #a31515">"            string escapedLine = line.Replace(@\"\\\", @\"\\\\\")"</span>,
<span style="color: #a31515">"                .Replace(\"\\\"\", \"\\\\\\\"\");"</span>,
<span style="color: #a31515">"            Console.WriteLine(\"\\\"{0}\\\",\", escapedLine);"</span>,
<span style="color: #a31515">"        }"</span>,
<span style="color: #a31515">"        Console.WriteLine(\"        };\");"</span>,
<span style="color: #a31515">""</span>,
<span style="color: #a31515">"        foreach (string line in S) Console.WriteLine(line);"</span>,
<span style="color: #a31515">""</span>,
<span style="color: #a31515">"        Console.WriteLine(\"    }\");"</span>,
<span style="color: #a31515">"        Console.WriteLine(\"}\");"</span>,<span style="color: #a31515">
        </span>};
        <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"using System;"</span>);
        <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"class P {"</span>);
        <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"    static void Main() {"</span>);

        <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"        string[] S = {"</span>);
        <span style="color: blue">foreach </span>(<span style="color: blue">string </span>line <span style="color: blue">in </span>S)
        {
            <span style="color: blue">string </span>escapedLine = line.Replace(<span style="color: #a31515">@"\"</span>, <span style="color: #a31515">@"\\"</span>)
                .Replace(<span style="color: #a31515">"\""</span>, <span style="color: #a31515">"\\\""</span>);
            <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"\"{0}\","</span>, escapedLine);
        }
        <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"        };"</span>);

        <span style="color: blue">foreach </span>(<span style="color: blue">string </span>line <span style="color: blue">in </span>S) <span style="color: #2b91af">Console</span>.WriteLine(line);

        <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"    }"</span>);
        <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"}"</span>);
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Pretty simple, isn&#8217;t it?</p>
<p>One interesting point is that if we add extra code into the program core, and add the same code into the definition of string S, we will still have a quine. For example, here is how you can extend to quine to print an arbitrary string to standard error, after printing its own source code to standard output:</p>
<pre class="code"><span style="color: blue">using </span>System;
<span style="color: blue">class </span><span style="color: #2b91af">P
</span>{
    <span style="color: blue">static void </span>Main()
    {
        <span style="color: blue">string</span>[] S = {
<span style="color: #a31515">"        Console.WriteLine(\"using System;\");"</span>,
<span style="color: #a31515">"        Console.WriteLine(\"class P {\");"</span>,
<span style="color: #a31515">"        Console.WriteLine(\"    static void Main() {\");"</span>,
<span style="color: #a31515">""</span>,
<span style="color: #a31515">"        Console.WriteLine(\"        string[] S = {\");"</span>,
<span style="color: #a31515">"        foreach (string line in S) {"</span>,
<span style="color: #a31515">"            string escapedLine = line.Replace(@\"\\\", @\"\\\\\")"</span>,
<span style="color: #a31515">"                .Replace(\"\\\"\", \"\\\\\\\"\");"</span>,
<span style="color: #a31515">"            Console.WriteLine(\"\\\"{0}\\\",\", escapedLine);"</span>,
<span style="color: #a31515">"        }"</span>,
<span style="color: #a31515">"        Console.WriteLine(\"        };\");"</span>,
<span style="color: #a31515">""</span>,
<span style="color: #a31515">"        foreach (string line in S) Console.WriteLine(line);"</span>,
<span style="color: #a31515">""</span>,
<span style="color: #a31515">"        Console.WriteLine(\"    }\");"</span>,
<span style="color: #a31515">"        Console.WriteLine(\"}\");"</span>,
<span style="color: #a31515">""</span>,
<span style="color: #a31515">"        Console.Error.WriteLine(\"This quine can do other things too!\");"</span>,
        };
        <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"using System;"</span>);
        <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"class P {"</span>);
        <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"    static void Main() {"</span>);

        <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"        string[] S = {"</span>);
        <span style="color: blue">foreach </span>(<span style="color: blue">string </span>line <span style="color: blue">in </span>S)
        {
            <span style="color: blue">string </span>escapedLine = line.Replace(<span style="color: #a31515">@"\"</span>, <span style="color: #a31515">@"\\"</span>)
                .Replace(<span style="color: #a31515">"\""</span>, <span style="color: #a31515">"\\\""</span>);
            <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"\"{0}\","</span>, escapedLine);
        }
        <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"        };"</span>);

        <span style="color: blue">foreach </span>(<span style="color: blue">string </span>line <span style="color: blue">in </span>S) <span style="color: #2b91af">Console</span>.WriteLine(line);

        <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"    }"</span>);
        <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">"}"</span>);

        <span style="color: #2b91af">Console</span>.Error.WriteLine(<span style="color: #a31515">"This quine can do other things too!"</span>);
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>So, we can write a program that knows how to print its source code, but also does other things. This is interesting for three reasons:</p>
<ol>
<li>It is an important result in theoretical computer science, known as the <a href="http://en.wikipedia.org/wiki/KRT">recursion theorem</a>. Recursion theorem can be used to prove a variety of interesting results. For example, using the recursion theorem is one way to prove that the halting problem is undecidable.
<li>Virus writers write programs that know how to replicate themselves, but also do other things, such as messing up your computer.
<li>You can write pointless but cool little programs, like my <a href="http://igoro.com/archive/self-printing-game-of-life-in-c">self-printing Game of Life</a>. </li>
</ol>
<p>By the way, the quine that I described in this article is by no means the shortest possible one in C#. Joey Wescott came up with <a href="http://yetanotherdeveloper.com/post/2008/01/20/My-Quine.aspx">a C# quine</a> that is only 166 characters long. I suggested two improvements, and we got it down to 149 characters (all one line):</p>
<pre class="code"><span style="color: blue">class </span><span style="color: #2b91af">P</span>{<span style="color: blue">static void </span>Main(){<span style="color: blue">var </span>S=<span style="color: #a31515">"class P{{static void Main(){{var S={1}{0}{1};System.Console</span></pre>
</p>
<pre class="code"><span style="color: #a31515"></span><span style="color: #a31515">.Write(S,S,'{1}');}}}}"</span>;System.<span style="color: #2b91af">Console</span>.Write(S,S,<span style="color: #a31515">'"'</span>);}}</pre>
<p>And there you have it &#8211; that&#8217;s how you write quines. In my next article, I will talk about an interesting little problem, and seven very different algorithms that can be used to solve it.</p>
<p><strong>Other articles you may like:</strong></p>
<p><a href="http://igoro.com/archive/numbers-that-cannot-be-computed/">Numbers that cannot be computed</a></p>
<p><a href="http://igoro.com/archive/skip-lists-are-fascinating/">Skip list are fascinating!</a></p>
<p><a href="http://igoro.com/archive/quicksort-killer/">Quicksort killer</a></p>
<p><a href="http://www.metaspring.com/blog/development/ruby/metamonday-ruby-quines/">Ruby quines</a> [metaspring.com]</p>
]]></content:encoded>
			<wfw:commentRss>http://igoro.com/archive/how-to-write-a-self-printing-program/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Self-printing Game of Life in C#</title>
		<link>http://igoro.com/archive/self-printing-game-of-life-in-c/</link>
		<comments>http://igoro.com/archive/self-printing-game-of-life-in-c/#comments</comments>
		<pubDate>Thu, 30 Oct 2008 08:46:51 +0000</pubDate>
		<dc:creator>Igor Ostrovsky</dc:creator>
				<category><![CDATA[Cool Stuff]]></category>
		<category><![CDATA[Cool]]></category>

		<guid isPermaLink="false">http://igoro.com/archive/self-printing-game-of-life-in-c/</guid>
		<description><![CDATA[Conway&#8217;s Game of Life has fascinated computer scientists for decades. Even though its rules are ridiculously simple, Conway&#8217;s universe gives rise to a variety of gliders, spaceships, oscillators, glider guns, and other forms of &#8220;life&#8221;. Self-printing programs are similarly curious, and &#8211; rather surprisingly &#8211; have an important place in the theory of computation. What [...]]]></description>
			<content:encoded><![CDATA[</p>
<p>Conway&#8217;s Game of Life has fascinated computer scientists for decades. Even though its rules are ridiculously simple, Conway&#8217;s universe gives rise to a variety of gliders, spaceships, oscillators, glider guns, and other forms of &#8220;life&#8221;. Self-printing programs are similarly curious, and &#8211; rather surprisingly &#8211; have an important place in the theory of computation.</p>
<p>What happens when you combine the two? You are about to find out, but one thing is for sure: the geekiness factor should be pretty high.</p>
<p>I wrote a little C# program that contains a Game-of-Life grid. The program advances the game grid to the next generation and prints out a copy of itself, with the grid updated. You can take the output, compile it with a C# compiler, run it, and you&#8217;ll get the next generation of the game. You can iterate the process, or change the initial grid state manually.</p>
<p><span id="more-82"></span></p>
<p>Here is the source code:</p>
<div style="font-size: 8pt">
<pre class="code"><span style="color: blue">using </span>System;<span style="color: blue">class </span><span style="color: #2b91af">G  </span><span style="color: green">/* GAME OF LIFE by Igor Ostrovsky */  </span>{<span style="color: blue">static string</span>[]S={
<span style="color: #a31515">"############################################################################"</span>,
<span style="color: #a31515">"#                                                               * *        #"</span>,
<span style="color: #a31515">"#  ***                                                         *           #"</span>,
<span style="color: #a31515">"#                                       *                      *           #"</span>,
<span style="color: #a31515">"#                                     * *                      *  *        #"</span>,
<span style="color: #a31515">"#                           **      **            **           ***         #"</span>,
<span style="color: #a31515">"#                          *   *    **            **                       #"</span>,
<span style="color: #a31515">"#               **        *     *   **                                     #"</span>,
<span style="color: #a31515">"#               **        *   * **    * *                                  #"</span>,
<span style="color: #a31515">"#                         *     *       *                                  #"</span>,
<span style="color: #a31515">"#                          *   *                                           #"</span>,
<span style="color: #a31515">"#                           **                                             #"</span>,
<span style="color: #a31515">"#   **     **                                                              #"</span>,
<span style="color: #a31515">"#    **   **                                        *  *                   #"</span>,
<span style="color: #a31515">"# *  * * * *  *                                         *                  #"</span>,
<span style="color: #a31515">"# *** ** ** ***                                     *   *                  #"</span>,
<span style="color: #a31515">"#  * * * * * *                                       ****                  #"</span>,
<span style="color: #a31515">"#   ***   ***                                                              #"</span>,
<span style="color: #a31515">"#                                                                          #"</span>,
<span style="color: #a31515">"#   ***   ***                                                              #"</span>,
<span style="color: #a31515">"#  * * * * * *            *                                                #"</span>,
<span style="color: #a31515">"# *** ** ** ***           *           *  *                             *** #"</span>,
<span style="color: #a31515">"# *  * * * *  *                           *                           *  * #"</span>,
<span style="color: #a31515">"#    **   **             ***          *   *                **            * #"</span>,
<span style="color: #a31515">"#   **     **                          ****                              * #"</span>,
<span style="color: #a31515">"#                                                                     * *  #"</span>,
<span style="color: #a31515">"############################################################################"</span>,
};<span style="color: blue">static void </span>Main(){<span style="color: blue">string </span>T=<span style="color: #a31515">"\",r=\"using System;class G  /* GAME OF LIFE b"</span>+
<span style="color: #a31515">"y Igor Ostrovsky \"+\"*/  {static string[]S={\\n\";int p=31,i,j,b,d;for(i=0;"</span>+
<span style="color: #a31515">"i&lt;27;i++){r+='\"'; for(j=0;j&lt;76;j++){if(S[i][j]!='#'){b=0;for(d=0;d&lt;9;d++)if"</span>+
<span style="color: #a31515">"(S[i-1+d/3][j-1+d%3]=='*')b++;r+=b==3 ||(S[i][j]=='*'&amp;&amp;b==4)?'*':' ';} else "</span>+
<span style="color: #a31515">"r+='#';}r+=\"\\\",\\n\";}r+=\"};static\"+\" void Main(){string T=\\\"\";fore"</span>+
<span style="color: #a31515">"ach(var c in T){if(c=='\\\\'||c=='\"'){r+='\\\\';p++;} r+=c; if(++p&gt;=77){r+="</span>+
<span style="color: #a31515">"\"\\\"+\\n\\\"\";p=1;}} foreach(var c in T){r+=c;if(++p%79==0)r+='\\n';}Cons"</span>+
<span style="color: #a31515">"ole.Write(r);}}"</span>,r=<span style="color: #a31515">"using System;class G  /* GAME OF LIFE by Igor Ostrovsky "</span>+
<span style="color: #a31515">"*/  {static string[]S={\n"</span>;<span style="color: blue">int </span>p=31,i,j,b,d;<span style="color: blue">for</span>(i=0;i&lt;27;i++){r+=<span style="color: #a31515">'"'</span>; <span style="color: blue">for</span>(j=0;
j&lt;76;j++){<span style="color: blue">if</span>(S[i][j]!=<span style="color: #a31515">'#'</span>){b=0;<span style="color: blue">for</span>(d=0;d&lt;9;d++)<span style="color: blue">if</span>(S[i-1+d/3][j-1+d%3]==<span style="color: #a31515">'*'</span>)b++;
r+=b==3 ||(S[i][j]==<span style="color: #a31515">'*'</span>&amp;&amp;b==4)?<span style="color: #a31515">'*'</span>:<span style="color: #a31515">' '</span>;} <span style="color: blue">else </span>r+=<span style="color: #a31515">'#'</span>;}r+=<span style="color: #a31515">"\",\n"</span>;}r+=<span style="color: #a31515">"};static"
</span>+<span style="color: #a31515">" void Main(){string T=\""</span>;<span style="color: blue">foreach</span>(<span style="color: blue">var </span>c <span style="color: blue">in </span>T){<span style="color: blue">if</span>(c==<span style="color: #a31515">'\\'</span>||c==<span style="color: #a31515">'"'</span>){r+=<span style="color: #a31515">'\\'</span>;p++
;} r+=c; <span style="color: blue">if</span>(++p&gt;=77){r+=<span style="color: #a31515">"\"+\n\""</span>;p=1;}} <span style="color: blue">foreach</span>(<span style="color: blue">var </span>c <span style="color: blue">in </span>T){r+=c;<span style="color: blue">if</span>(++p%79==0)
r+=<span style="color: #a31515">'\n'</span>;}<span style="color: #2b91af">Console</span>.Write(r);}}</pre>
</div>
<p><font color="#0000ff"></font>&nbsp;</p>
<p>And is here the output the program prints. The output is the same as the source code, except that the game has advanced to the next generation:</p>
<div style="font-size: 8pt">
<pre>using System;class G  /* GAME OF LIFE by Igor Ostrovsky */  {static string[]S={
"############################################################################",
"#   *                                                                      #",
"#   *                                                          **          #",
"#   *                                  *                      ***          #",
"#                                    * *                      ** *         #",
"#                           *       * *           **           ***         #",
"#                          **      *  *           **            *          #",
"#               **        **    **  * *                                    #",
"#               **       ***    **   * *                                   #",
"#                         **    **     *                                   #",
"#                          **                                              #",
"#                           *                                              #",
"#   ***   ***                                                              #",
"#                                                                          #",
"# *    * *    *                                        **                  #",
"# *    * *    *                                      ** **                 #",
"# *    * *    *                                      ****                  #",
"#   ***   ***                                         **                   #",
"#                                                                          #",
"#   ***   ***                                                              #",
"# *    * *    *                                                         *  #",
"# *    * *    *                                                        *** #",
"# *    * *    *          * *             **                            * **#",
"#                         *            ** **                            ***#",
"#   ***   ***             *            ****                             ** #",
"#                                       **                                 #",
"############################################################################",
};static void Main(){string T="\",r=\"using System;class G  /* GAME OF LIFE b"+
"y Igor Ostrovsky \"+\"*/  {static string[]S={\\n\";int p=31,i,j,b,d;for(i=0;"+
"i&lt;27;i++){r+='\"'; for(j=0;j&lt;76;j++){if(S[i][j]!='#'){b=0;for(d=0;d&lt;9;d++)if"+
"(S[i-1+d/3][j-1+d%3]=='*')b++;r+=b==3 ||(S[i][j]=='*'&amp;&amp;b==4)?'*':' ';} else "+
"r+='#';}r+=\"\\\",\\n\";}r+=\"};static\"+\" void Main(){string T=\\\"\";fore"+
"ach(var c in T){if(c=='\\\\'||c=='\"'){r+='\\\\';p++;} r+=c; if(++p&gt;=77){r+="+
"\"\\\"+\\n\\\"\";p=1;}} foreach(var c in T){r+=c;if(++p%79==0)r+='\\n';}Cons"+
"ole.Write(r);}}",r="using System;class G  /* GAME OF LIFE by Igor Ostrovsky "+
"*/  {static string[]S={\n";int p=31,i,j,b,d;for(i=0;i&lt;27;i++){r+='"'; for(j=0;
j&lt;76;j++){if(S[i][j]!='#'){b=0;for(d=0;d&lt;9;d++)if(S[i-1+d/3][j-1+d%3]=='*')b++;
r+=b==3 ||(S[i][j]=='*'&amp;&amp;b==4)?'*':' ';} else r+='#';}r+="\",\n";}r+="};static"
+" void Main(){string T=\"";foreach(var c in T){if(c=='\\'||c=='"'){r+='\\';p++
;} r+=c; if(++p&gt;=77){r+="\"+\n\"";p=1;}} foreach(var c in T){r+=c;if(++p%79==0)
r+='\n';}Console.Write(r);}}
</pre>
</div>
<p>&nbsp;</p>
<p>If you want to see the program iterate, save the source code into a file named life.cs, and run this command repeatedly from a Visual Studio console:</p>
<pre class="code">csc.exe life.cs &amp;&amp; (life &gt; life.cs) &amp;&amp; life</pre>
<p>Cool, isn&#8217;t it? I have a follow-up article nearly ready that explains how to write programs like this one&#8230; just in case you ever wanted to. <img src='http://igoro.com/wordpress/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p>[Update] The follow-up <a href="http://igoro.com/archive/how-to-write-a-self-printing-program/">How to write a self-printing program</a> is up.</p>
<p><strong>More articles:</strong></p>
<p><a title="Permanent Link- Numbers that cannot be computed" href="http://igoro.com/archive/numbers-that-cannot-be-computed/">Numbers that cannot be computed</a></p>
<p><a href="http://igoro.com/archive/skip-lists-are-fascinating/">Skip list are fascinating!</a></p>
<p><a href="http://igoro.com/archive/quicksort-killer/">Quicksort killer</a></p>
]]></content:encoded>
			<wfw:commentRss>http://igoro.com/archive/self-printing-game-of-life-in-c/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Numbers that cannot be computed</title>
		<link>http://igoro.com/archive/numbers-that-cannot-be-computed/</link>
		<comments>http://igoro.com/archive/numbers-that-cannot-be-computed/#comments</comments>
		<pubDate>Sun, 19 Oct 2008 04:59:54 +0000</pubDate>
		<dc:creator>Igor Ostrovsky</dc:creator>
				<category><![CDATA[Cool Stuff]]></category>
		<category><![CDATA[Cool]]></category>

		<guid isPermaLink="false">http://igoro.com/archive/numbers-that-cannot-be-computed/</guid>
		<description><![CDATA[Did you know that there are numbers that cannot be computed by any computer program? It is weird, but true. And by number, I mean just an ordinary real number. As a perhaps unnecessarily simple example, the result of the division 1/7 looks like this: &#160;&#160;&#160;&#160;&#160;&#160;&#160; 0.1428571428571428571428571428571414285714285714285714285714285714&#8230; We can easily implement a program that prints [...]]]></description>
			<content:encoded><![CDATA[<p>Did you know that there are numbers that cannot be computed by any computer program? It is weird, but true.</p>
<p>And by number, I mean just an ordinary real number. As a perhaps unnecessarily simple example, the result of the division 1/7 looks like this:</p>
<p><em>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 0.1428571428571428571428571428571414285714285714285714285714285714&#8230;</em> </p>
<p>We can easily implement a program that prints this number. The decimal expansion of 1/7 is infinite, so the program will have to run in an infinite loop to print the &#8220;whole&#8221; number. Here is a C# implementation:</p>
<pre class="code"><span style="color: blue">    static void </span>Main()
<span style="color: blue"></span><span style="color: blue"></span>    {<span style="color: blue"></span>
        <span style="color: #2b91af">Console</span>.Write(<span style="color: #a31515">"0."</span>);
        <span style="color: blue">while </span>(<span style="color: blue">true</span>) <span style="color: #2b91af">Console</span>.Write(<span style="color: #a31515">"142857"</span>);
    }</pre>
<p><span id="more-81"></span></p>
<p><a href="http://11011.net/software/vspaste"></a>It is a bit of a philosophical question whether this program is really &#8220;computing&#8221; 1/7 or whether it has the answer hard-coded. You can certainly write a program that will compute the answer more legitimately by long division. The part that really matters is that there is some program that prints the infinite decimal expansion of 1/7, which makes 1/7 a <em>computable</em> number.</p>
<p>Similarly, you can write programs that will print the infinite decimal expansion of any rational number, sqrt(2), any <a href="http://en.wikipedia.org/wiki/Algebraic_number">algebraic number</a>, π, e, and just about any other number that you can describe. For example, to compute π, you could use one of the known <a href="http://en.wikipedia.org/wiki/Computing_%CF%80">approximation algorithms</a>. You would compute π to greater and greater accuracy, and print more and more digits to the screen. As a side note, we are assuming that the computer that will execute your program has an unlimited amount of memory. While not very realistic, this abstraction is analogous to the famous Turing machine, and extremely useful to understand certain deep truths about computation.</p>
<p>Interestingly, there are numbers that are non-computable. A number is non-computable if there is no program that prints its infinite decimal expansion (adding trailing zeros if a finite expansion is possible). How do we know that there are such numbers? The key insight is that there are more real numbers than there are C# programs. That is pretty surprising, given that both the number of real numbers and the number of C# programs are infinite. Nevertheless, it is true.</p>
<p>C# programs are <em>countable</em>. That means that we can assign a different positive integer to each program. The shortest valid C# program will be 1, the next shortest will be 2, and so forth. If there are multiple valid programs of the same length, we will sort the programs lexicographically and assign integers in that order. By the way, there are many different ways in which to define a &#8220;valid program&#8221;. One approach is to say that to be valid, the program must compile, run without exceptions, and print an infinite sequence of digits, separated at exactly one place with a decimal point.</p>
<p>Unlike C# programs, real numbers are <em>uncountable</em>. There is no way to assign a different integer to each real number&#8230; there are just too many real numbers! This fact was proved by Georg Cantor in a couple different ways, the most famous of which is the <a href="http://en.wikipedia.org/wiki/Cantors_Diagonal_argument">diagonalization argument</a>.</p>
<p>Not only do non-computable numbers exist, but in fact they are vastly more abundant than computable numbers. Many, many real numbers are simply infinite sequences of seemingly random digits, with no pattern or special property. But, even though there are so many uncountable numbers, their examples tend to be weird and a little strenuous to explain.</p>
<p>As one such example, consider a number whose part before the decimal point is 0. We choose i-th digit after the decimal point to be different from the digit in the same position in the number printed by program i (by &#8220;program i&#8221;, I mean the program associated with integer i, as described earlier in the article). So, each digit after the decimal point guarantees that the constructed number will differ from the number printed by a particular program. This demonstrates that the constructed number will be different from any number printed by a computer program! By the way, this construction is basically Cantor&#8217;s diagonalization argument, only recast in a different terminology.</p>
<p>Theoretical foundations of computer science, which underlie everything we do as programmers, are nothing short of amazing. If you would like to read more about computability and related concepts, check out Charles Petzold&#8217;s book, <a href="http://www.amazon.com/Annotated-Turing-Through-Historic-Computability/dp/0470229055">The Annotated Turing</a>. The original Alan Turing&#8217;s paper that introduces computable numbers is available <a href="http://www.abelard.org/turpap2/tp2-ie.asp">here</a>, but Petzold&#8217;s book is a lot easier to read.</p>
<p>[Update] See the forum on the <a href="http://www.reddit.com/r/programming/comments/782mt/numbers_that_cannot_be_computed_by_a_program/">reddit page</a> of this article for additional in-depth discussion of this topic.</p>
<p><strong>More articles:</strong></p>
<p><a href="http://igoro.com/archive/skip-lists-are-fascinating/">Skip list are fascinating!</a></p>
<p><a href="http://igoro.com/archive/data-structure-zoo-ordered-set/">Data structure zoo: ordered set</a></p>
<p><a href="http://igoro.com/archive/quicksort-killer/">Quicksort killer</a></p>
]]></content:encoded>
			<wfw:commentRss>http://igoro.com/archive/numbers-that-cannot-be-computed/feed/</wfw:commentRss>
		<slash:comments>55</slash:comments>
		</item>
	</channel>
</rss>
