<?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>Garrett Bluma</title>
	<atom:link href="http://garrettbluma.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://garrettbluma.com</link>
	<description>Web Developer</description>
	<lastBuildDate>Sat, 10 Aug 2013 16:49:54 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.4.2</generator>
		<item>
		<title>Convergence algorithms are neat</title>
		<link>http://garrettbluma.com/2013/05/23/convergence-algorithms-are-neat/</link>
		<comments>http://garrettbluma.com/2013/05/23/convergence-algorithms-are-neat/#comments</comments>
		<pubDate>Thu, 23 May 2013 17:51:35 +0000</pubDate>
		<dc:creator>Garrett Bluma</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Haskell]]></category>

		<guid isPermaLink="false">http://garrettbluma.com/?p=16936</guid>
		<description><![CDATA[Convergence algorithms are really cool. There are often used in numerical calculations for fast approximations. Netwon&#8217;s method is still one of the fastest ways to find roots (zeros) of a real-valued continuous functions. The functions work by doing a particular action over and over, comparing the outputs, until the two results are within some predefined tolerance. We can use this outside of a numerical situations as well. This is useful for situations where you have results that are buggy or inconsistent. As I&#8217;m writing this I&#8217;m running a script that tries to convert an SVN tree to Git. Sometimes it [...]]]></description>
			<content:encoded><![CDATA[<p>Convergence algorithms are really cool. There are often used in numerical calculations for fast approximations. Netwon&rsquo;s method is still one of the fastest ways to find roots (zeros) of a real-valued continuous functions. The functions work by doing a particular action over and over, comparing the outputs, until the two results are within some predefined tolerance.</p>
<p>We can use this outside of a numerical situations as well. This is useful for situations where you have results that are buggy or inconsistent. As I&rsquo;m writing this I&rsquo;m running a script that tries to convert an SVN tree to Git. Sometimes it fails and dies on me, and I really don&rsquo;t want to baby it. Instead, since I know it&rsquo;s <em>idempotent</em> (repeated attempts will result in the same output) I can just tell it to run until the results converge. If the results stop changing, then it&rsquo;s done.</p>
<p>Here is some pseudocode:</p>
<pre><code>def converge( action ) {
    var previous_result = null
    var result = action() 
    while (previous_result != result) {
        previous_result = result
        result =action()
    }
    return result
}
</code></pre>
<p>And a functional variant (for fun):</p>
<pre><code>foo :: IO Int
foo = do 
  putStrLn "calling foo, which could return strange results"
  return 1

converge compare prev action = do
  result &lt;- action
  if prev `compare` result 
     then return result
     else converge compare result action

main = converge (==) 0 foo &gt;&gt;= print
</code></pre>
<p>One thing to be careful about is the chance that your output will never converge. For example, if your function depends on a millisecond counter you may not <em>ever</em> get your results. It is always a good idea to add an upper limit on the number of attempts.</p>
]]></content:encoded>
			<wfw:commentRss>http://garrettbluma.com/2013/05/23/convergence-algorithms-are-neat/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>On good days and bad days</title>
		<link>http://garrettbluma.com/2013/05/23/on-good-days-and-bad-days/</link>
		<comments>http://garrettbluma.com/2013/05/23/on-good-days-and-bad-days/#comments</comments>
		<pubDate>Thu, 23 May 2013 15:17:13 +0000</pubDate>
		<dc:creator>Garrett Bluma</dc:creator>
				<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://garrettbluma.com/?p=16933</guid>
		<description><![CDATA[“Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.” &#8212; Brian Kernighan Coding cleverly is a problem for all programmers, but perhaps more so for advanced programmers than novices. Novices tend to stick with what works and don&#8217;t reach for deep abstractions when they aren&#8217;t needed. However, advanced programmers do this often, and this actually makes their job harder. Clever code demands clever programmers&#8212;once we rely on cleverness it&#8217;s no longer a bonus. Cleverness is generally [...]]]></description>
			<content:encoded><![CDATA[<blockquote><p>“Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.” &mdash; Brian Kernighan</p>
</blockquote>
<p>Coding cleverly is a problem for all programmers, but perhaps more so for advanced programmers than novices. Novices tend to stick with what works and don&rsquo;t reach for deep abstractions when they aren&rsquo;t needed. However, advanced programmers do this often, and this actually makes their job harder. Clever code <em>demands</em> clever programmers&mdash;once we rely on cleverness it&rsquo;s no longer a bonus.</p>
<p>Cleverness is generally an asset in programming. We don&rsquo;t get to rely on the usual senses of spatial awareness or linguistic flow when we write code&mdash;instead we have to rely on logic and inference. Cause and effect. Evidence, reason, and truth. It takes cleverness to identify why race conditions occur in a distributed system. It takes significantly less cleverness to write a distributed system that exibits race conditions.</p>
<p>We might think to ourselves, &ldquo;If I just add a level of indirection <em>here</em>, then we get a useful abstraction.&rdquo; This may be true, but should ask some questions before comitting to a change like that:</p>
<p><strong>Is it disoverable?</strong> &mdash; If I make this change, will others discover it without my telling them?</p>
<p><strong>Does it improve the project?</strong> &mdash; Will the indirection save us time or slow us down?</p>
<p><strong>Does it require the cleverness needed to understand the project?</strong> &mdash; When I debug this, will I need to trace through the code or can I skip a step and just rely on a rule of thumb?</p>
<p>Those of us who have made a career our of cleverness may think that we are <em>always</em> consitently smart&mdash;everyday is a good day&mdash;but this is not the case. Cleverness comes in fleeting moments of inspiration, not as an infinite resource which we can draw upon when we like. The veteran programmers are acutely aware that, indeed, when a programmer <em>needs</em> to be clever that is precisely the moment that they aren&rsquo;t. Grit and stubbornness are better attributes than cleverness. (Group discussion and measured analysis is better still.)</p>
<p>So when we design our programs we shouldn&rsquo;t <em>expect</em> that our future selves will be clever enough to figure out the interdependencies among objects, the changing network architecture, the concurrent projects that are all being worked on at the same time with the same code, etc. Very likely, when we need to make tough decisions, we will still be slogging through a confusing email thread, distracted by meetings every 30 minutes, and having only slept about four hours the night before. We won&rsquo;t be bringing our <em>A</em> game like we think we will.</p>
<p>Instead, we should expect our own inadequacy and use our current  cleverness to make the code maintainable for the bad days. Also, if you think about it, this is an investment for the future becuase we&rsquo;ll have more free brainpower for other problems.</p>
<blockquote><p>&ldquo;many a programmer derives a major part of his professional excitement from not quite understanding what he is doing, from the daring risks he takes and from the struggle to find the bugs he should not have introduced in the first place.&rdquo; &mdash; E. W. Dijkstra</p>
</blockquote>
]]></content:encoded>
			<wfw:commentRss>http://garrettbluma.com/2013/05/23/on-good-days-and-bad-days/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Abstraction and cognitive load</title>
		<link>http://garrettbluma.com/2013/05/10/abstraction-and-cognitive-load/</link>
		<comments>http://garrettbluma.com/2013/05/10/abstraction-and-cognitive-load/#comments</comments>
		<pubDate>Fri, 10 May 2013 20:17:15 +0000</pubDate>
		<dc:creator>Garrett Bluma</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://garrettbluma.com/?p=16929</guid>
		<description><![CDATA[When programmers need to make a system simpler, they are told to reach for abstraction as a means of doing this. But abstraction is an odd thing; it escapes easy definition. It's something we use to make programs better, more comprehensible, more general, more flexible, and hopefully easier to reuse. "In computer science, abstraction is the process by which data and programs are defined with a representation similar in form to its meaning (semantics), while hiding away the implementation details." &#8211; Wikipedia But how do we get abstraction? Abstraction is fundamentally built up from constraints in a system and these [...]]]></description>
			<content:encoded><![CDATA[<p>When programmers need to make a system simpler, they are told to reach for abstraction as a means of doing this. But abstraction is an odd thing; it escapes easy definition. It's something we use to make programs better, more comprehensible, more general, more flexible, and hopefully easier to reuse.</p>
<blockquote><p>"In computer science, abstraction is the process by which data and programs are defined with a representation similar in form to its meaning (semantics), while hiding away the implementation details." &ndash; <a href="http://en.wikipedia.org/wiki/Abstraction_%28computer_science%29">Wikipedia</a></p></blockquote>
<p>But how do we get abstraction?</p>
<p>Abstraction is fundamentally built up from constraints in a system and these constraints guide future changes into patterns. Creating an abstraction is about finding the places where things can become separated. An example of this is the separation of code and data, or commands and queries. This is a truly a challenging task, because not only must a person understand to the structure of the code and its semantics, but they must also predict how someone else will interpret them.</p>
<p>While there may be some technical merit to abstraction, we must admit that abstraction is largely something we do for other people. When we struggle to abstract a system we can't just say, <em>the tools are ineffective</em>, we must also ask ourselves <em>how can I communicate better?</em></p>
<p>It is always enticing to reach for new tools to produce cleaner abstractions&mdash;this is good to some degree&mdash;Haskell, Ocaml, and Scala do provide many wonderful new tools for developing abstractions. They even report when those abstractions are being violated&mdash;But the danger of this is letting the compiler tell <em>us</em> how to build our applications. Abstraction should be something we <em>impose</em> on the code, despite its unwillingness to be abstracted. We should not do it <em>reactively</em>. When we react, we give up some of our intended design. Although it is purely conjecture, it may even be the case that languages that interrupt us with numerous error messages actually train us not have good design. We get distracted by details and lose sight of the bigger picture.</p>
<p>I am a proponent of static types, but I think it is worth heeding old advice. Get away from the computer. Pull out a pen and paper. And design the thing without all the distractions, even helpful ones. When you go back to the computer you'll have an advantage in all respects.</p>
]]></content:encoded>
			<wfw:commentRss>http://garrettbluma.com/2013/05/10/abstraction-and-cognitive-load/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A couple notes on teaching programming</title>
		<link>http://garrettbluma.com/2013/03/29/a-couple-notes-on-teaching-programming/</link>
		<comments>http://garrettbluma.com/2013/03/29/a-couple-notes-on-teaching-programming/#comments</comments>
		<pubDate>Fri, 29 Mar 2013 06:30:24 +0000</pubDate>
		<dc:creator>Garrett Bluma</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://garrettbluma.com/?p=16913</guid>
		<description><![CDATA[I spent some time tonight teaching the basics of programming to a friend. We were focusing on C# in particular, covering the basics of object-oriented programming, instantiation, control structures, and the like... It's always refreshing to take a step back and re-evaluate the fundamentals with fresh eyes. Many of the things that I have become accustomed to are actually incredibly strange, and some of the things I used to find problematic are actually quite easy to teach. For example. At one point we got stuck on the intricacies of how variables are overridden in child objects. Even though the variable [...]]]></description>
			<content:encoded><![CDATA[<p>I spent some time tonight teaching the basics of programming to a friend. We were focusing on C# in particular, covering the basics of object-oriented programming, instantiation, control structures, and the like... It's always refreshing to take a step back and re-evaluate the fundamentals with fresh eyes. Many of the things that I have become accustomed to are actually incredibly strange, and some of the things I used to find problematic are actually quite easy to teach.</p>
<p>For example. At one point we got stuck on the intricacies of how variables are overridden in child objects. Even though the variable was updated in the subclass, the parent values were used instead&mdash;this was counter-intuitive and rather difficult to convey. We had to manually trace the references back from the point of usage to find out that, in our context, our object was being treated as the parent class. It inherited a set of supposedly hidden variables, and it was returning those variables when we expected them to be hidden. This was a bit too much for my friend to absorb, so we moved on.</p>
<p>Object instantiation was surprisingly easy to describe however. It made sense that objects can hold properties about themselves in a sort of namespace. Even that the objects have local functions which operate on local data. The process of constructing an instance of a class, as if it were a template, was also simple and direct.</p>
<p>We didn't cover exceptions. I suspect these will cause some trouble down the road...</p>
<p>On the other hand, we talked a bit about functional programming. I always hesitate to talk about stuff like this because, even if I find it interesting, that doesn't mean it is worth distracting someone else. But it was funny to realize how very few tools are needed to get a big pay-off: function application, local identifiers, function arguments, and namespaces. And it's worth mentioning that tracing references and variable assignment was simpler too. </p>
<p>Obviously this is very subjective, but the experience was interesting. We certainly can't extrapolate any kind of bigger themes out of this, like "FP is always easier," but my initial hesitation seems somewhat unwarranted.</p>
]]></content:encoded>
			<wfw:commentRss>http://garrettbluma.com/2013/03/29/a-couple-notes-on-teaching-programming/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Installing E16 Window Manager in Ubuntu</title>
		<link>http://garrettbluma.com/2013/03/23/installing-e16-window-manager-in-ubuntu/</link>
		<comments>http://garrettbluma.com/2013/03/23/installing-e16-window-manager-in-ubuntu/#comments</comments>
		<pubDate>Sun, 24 Mar 2013 03:52:32 +0000</pubDate>
		<dc:creator>Garrett Bluma</dc:creator>
				<category><![CDATA[Linux]]></category>

		<guid isPermaLink="false">http://garrettbluma.com/?p=16899</guid>
		<description><![CDATA[Enlightentment 16 (e16) is one of my favorite window managers. It's not the newest WM on the block, in fact E17 is designed to replace it, but there is something nice about going back to a light and fast window browser. I was looking for some notes on how to install it and couldn't find anything. I thought I'd share how. Forget about installing packages, most modern distros are deprecating this baby as quickly as they can. You'll have to download the source. Hopefully that isn't too hard. It's still hosted on sourceforge at the time of this writing (March [...]]]></description>
			<content:encoded><![CDATA[<p>Enlightentment 16 (e16) is one of my favorite window managers.</p>
<div style="text-align:center"><img src="http://gbluma-public.s3.amazonaws.com/tumblr/2013/08-10-2013_e16.png" style="width: 50%;"></div>
<p>It's not the newest WM on the block, in fact <a href="http://www.enlightenment.org/">E17</a> is designed to replace it, but there is something nice about going back to a light and fast window browser.</p>
<p>I was looking for some notes on how to install it and couldn't find anything. I thought I'd share how.</p>
<p><strong>Forget about installing packages</strong>, most modern distros are deprecating this baby as quickly as they can. You'll have to download the source. Hopefully that isn't too hard. It's still hosted on sourceforge at the time of this writing (March 23, 2013).</p>
<p><strong><a href="http://prdownloads.sourceforge.net/enlightenment/e16-1.0.11.tar.gz?download">Download Here</a></strong></p>
<p><strong>Extract the source files</strong></p>
<p><code>tar -xzf e16-1.0.11.tar.gz<br />
cd e16-1.0.11</code></p>
<p><strong>Build e16</strong></p>
<p><code>./configure<br />
make<br />
sudo make install</code></p>
<p><strong>Update GDM </strong>(the login screen) to be aware of the new window manager.</p>
<p><code>sudo cat << EOF > /usr/share/xsessions/e16.desktop<br />
[Desktop Entry]<br />
Name=E16<br />
Comment=Enlightenment 16 Window Manager<br />
Exec=starte16<br />
Icon=<br />
Type=Application<br />
X-Ubuntu-Gettext-Domain=gnome-session-3.0<br />
EOF</code></p>
<p>The last thing you should do is <strong>update the menus</strong>. Right click the desktop. Go to <code>Maintenance > Regenerate Menus</code>. E16 will then know about all of your installed applications.</p>
]]></content:encoded>
			<wfw:commentRss>http://garrettbluma.com/2013/03/23/installing-e16-window-manager-in-ubuntu/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Hindley-Milner type system in PHP</title>
		<link>http://garrettbluma.com/2013/01/29/a-hindley-milner-type-system-in-php/</link>
		<comments>http://garrettbluma.com/2013/01/29/a-hindley-milner-type-system-in-php/#comments</comments>
		<pubDate>Tue, 29 Jan 2013 20:20:26 +0000</pubDate>
		<dc:creator>Garrett Bluma</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://garrettbluma.com/?p=16848</guid>
		<description><![CDATA[PHP is famously bad at preserving type safety. Having spent the last few years working in functional languages with strong typing, I've gotten more familiar types and how to use them for great good. However, in my day job I still primarily write PHP. How to reconcile these differences? Well, implement a type system and embed it! Below is a Hindley-Milner type system in PHP, which I ported from the Python version that Rob Smallshire wrote. This is not professional piece of code, however it does prove that the type system can find faults in some examples. The syntax is [...]]]></description>
			<content:encoded><![CDATA[<p>PHP is famously bad at preserving type safety.</p>
<p>Having spent the last few years working in functional languages with strong typing, I've gotten more familiar types and how to use them for great good. However, in my day job I still primarily write PHP. How to reconcile these differences? Well, implement a type system and embed it!</p>
<p>Below is a <a href="http://en.wikipedia.org/wiki/Hindley%E2%80%93Milner">Hindley-Milner type system</a> in PHP, which I ported from the <a href="http://www.smallshire.org.uk/sufficientlysmall/2010/04/11/a-hindley-milner-type-inference-implementation-in-python/">Python version</a> that <a href="http://www.smallshire.org.uk/sufficientlysmall/about-me/">Rob Smallshire</a> wrote. </p>
<p>This is not professional piece of code, however it does prove that the type system can find faults in some examples. The syntax is not very friendly however, thus the next logical step would be to implement a language which could export type expressions and PHP code... we'll see if I ever get around to that.</p>
<p>Anyway, feel free to leave comments if you find this useful or interesting.</p>
<pre>
&lt;?php
 
/** Lambda abstraction */
class Lambda
{
	function __construct($v, $body) {
		$this->v = $v;
		$this->body = $body;
	}
 
	function __toString() {
		return "(fn {$this->v} => {$this->body})";
	}
}
 
/** Identfier */
class Ident
{
	function __construct($name) {
		$this->name = $name;
	}
 
	function __toString() {
		return $this->name;
	}
}
 
 
/** Function application */
class Apply
{
	function __construct($fn, $arg) {
		$this->fn = $fn;
		$this->arg = $arg;
	}
 
	function __toString() {
		return "({$this->fn} {$this->arg})";
	}
}
 
/** Let binding */
class Let
{
	function __construct($v, $defn, $body) {
		$this->v = $v;
		$this->defn = $defn;
		$this->body = $body;
	}
 
	function __toString() {
		return "(let {$this->v} = {$this->defn} in {$this->body})";
	}
}
 
/** Letrec binding */
class Letrec
{
	function __construct($v, $defn, $body) {
		$this->v = $v;
		$this->defn = $defn;
		$this->body = $body;
	}
 
	function __toString() {
		return "(letrec {$this->v} = {$this->defn} in {$this->body})";
	}
}
 
 
//=======================================================
// Exception types
 
/** Raised if the type inference algorithm cannot infer types successfully */
class TypeError extends Exception
{
	function __construct($message) {
		$this->message = $message;
	}
 
	function __toString() {
		return (string) $this->message;
	}
}
 
/** Raised if the type environment supplied for is incomplete */
class ParseError extends Exception
{
	function __construct($message) {
		$this->message = $message;
	}
 
	function __toString() {
		return (string) $this->message;
	}
}
 
 
//=======================================================
// Types and type constructors
 
/**
 * A type variable standing for an arbitrary type.
 *
 * All type variables have a unique id, but names are only assigned lazily,
 * when required.
 */
class TypeVariable
{
	static $next_variable_id = 0;
	static $next_variable_name = 'a';
 
	function __construct() {
		$this->id = TypeVariable::$next_variable_id;
		TypeVariable::$next_variable_id += 1;
		$this->instance = null;
		$this->name = null;
	}
 
	/** Names are allocated to TypeVariables lazily, so that only TypeVariables present */
	function getName() {
		if ($this->name === null) {
			$this->name = TypeVariable::$next_variable_name;
			TypeVariable::$next_variable_name = chr( ord(TypeVariable::$next_variable_name) + 1);
		}
		return $this->name;
	}
 
	function __toString() {
		if ($this->instance === null) {
			return (string) $this->instance;
		} else {
			return $this->name;
		}
	}
 
	function __repr() {
		return "TypeVariable(id = {$this->id})";
	}
}
 
 
/** An n-ary type constructor which builds a new type from old */
class TypeOperator
{
 
	function __construct($name, $types) {
		$this->name = $name;
		if (is_array($types))
			$this->types = $types;
		else
			$this->types = array($types);
	}
 
	function __toString() {
		$num_types = count($this->types);
		if ($num_types === 0) {
			return $this->name;
		} else if ($num_types == 2) {
			return (string) $this->types[0] . " " . $this->name . " " . (string) $this->types[1];
		} else {
			return ($this->name . ' ' . implode(" ", $this->types));
		}
	}
}
 
 
/** A binary type constructor which builds function types */
class Func extends TypeOperator
{
	function __construct($from_type, $to_type) {
		parent::__construct("->", $from_type, $to_type);
	}
}
 
 
// Basic types are constructed with a nullary type constructor
$Integer = new TypeOperator("int", array());  # Basic integer
$Bool    = new TypeOperator("bool", array()); # Basic bool
$String  = new TypeOperator("string", array());
 
 
//=======================================================#
// Type inference machinery
 
 
/**
 * Computes the type of the expression given by node.
 *
 * The type of the node is computed in the context of the context of the
 * supplied type environment env. Data types can be introduced into the
 * language simply by having a predefined set of identifiers in the initial
 * environment. environment; this way there is no need to change the syntax or, more
 * importantly, the type-checking program when extending the language.
 *
 * Args:
 *    node: The root of the abstract syntax tree.
 *    env: The type environment is a mapping of expression identifier names
 *       to type assignments.
 *       to type assignments.
 *   non_generic: A set of non-generic variables, or None
 *
 * Returns:
 *   The computed type of the expression.
 *
 */
function analyse($node, $env, $non_generic=null) {
 
	if ($non_generic === null)
		$non_generic = array();
 
	if ($node instanceof Ident) {
		return readType($node->name, $env, $non_generic);
	}
	else if ($node instanceof Apply) {
		$fun_type = analyse( $node->fn, $env, $non_generic );
		$arg_type = analyse( $node->arg, $env, $non_generic );
		$result_type = new TypeVariable();
		unify(new Func($arg_type, $result_type), $fun_type);
		return $result_type;
	}
	else if ($node instanceof Lambda) {
		$arg_type = new TypeVariable();
		$new_env = $env;
		$new_env[$node->v] = $arg_type;
		$new_non_generic = $non_generic;
		$new_non_generic[] = $arg_type;
		$result_type = analyse($node->body, $new_env, $new_non_generic);
		return new Func($arg_type, $result_type);
	}
	else if ($node instanceof Let) {
		$defn_type = analyse($node->defn, $env, $non_generic);
		$new_env = $env;
		$new_env[$node->v] = $defn_type;
		return analyse($node->body, $new_env, $non_generic);
	}
	else if ($node instanceof Letrec) {
		$new_type = new TypeVariable();
		$new_env = $env;
		$new_env[$node->v] = $new_type;
		$new_non_generic = $non_generic;
		$new_non_generic[] = $new_type;
		$defn_type = analyse($node->defn, $new_env, $new_non_generic);
		unify($new_type, $defn_type);
		return analyse($node->body, $new_env, $non_generic);
	}
	die("Unhandled syntax node " . gettype(t));
}
 
 
/**
 * Get the type of identifier name from the type environment env.
 *
 * Args:
 *     name: The identifier name
 *     env: The type environment mapping from identifier names to types
 *     non_generic: A set of non-generic TypeVariables
 *
 * Raises:
 *     ParseError: Raised if name is an undefined symbol in the type
 *         environment.
 */
function readType($name, $env, $non_generic) {
	global $Integer;
	if (isset($env[$name])) {
		return fresh($env[$name], $non_generic);
	} elseif (ctype_digit($name) || is_int($name)) {
		return $Integer;
	} else {
		throw new Exception("Undefined symbol $name");
	}
}
 
 
/**
 * Makes a copy of a type expression.
 *
 * The type t is copied. The the generic variables are duplicated and the
 * non_generic variables are shared.
 *
 * Args:
 *    t: A type to be copied.
 *    non_generic: A set of non-generic TypeVariables
 */
function fresh( $t, $non_generic) {
	$mappings = array(); # A mapping of TypeVariables to TypeVariables
 
	$freshrec = 
		function ($tp) use (&$mappings, &$non_generic, &$freshrec) {
			$p = prune($tp);
			if ($p instanceof TypeVariable) {
				if (isGeneric($p, $non_generic)) {
					if (count($mappings) === 0 || !isset($mappings[$p])) {
						@$mappings[$p] = new TypeVariable();
					}
					return @$mappings[$p];
				} else {
					return $p;
				}
			}
			else if ($p instanceof TypeOperator) {
				$fresh_types = array();
				foreach($p->types as $x) {
					$fresh_types[] = $freshrec($x);
				}
				return new TypeOperator($p->name, $fresh_types);
			}
		};
 
	return $freshrec($t);
}
 
/**
 * helper function to zip in php
 */
function zip() {
	$args = func_get_args();
	$zipped = array();
	$n = count($args);
	for ($i=0; $i<$n; ++$i) {
		reset($args[$i]);
	}
	while ($n) {
		$tmp = array();
		for ($i=0; $i<$n; ++$i) {
			if (key($args[$i]) === null) {
				break 2;
			}
			$tmp[] = current($args[$i]);
			next($args[$i]);
		}
		$zipped[] = $tmp;
	}
	return $zipped;
}
 
 
/**
 * Unify the two types t1 and t2.
 *
 * Makes the types t1 and t2 the same.
 *
 * Args:
 *    t1: The first type to be made equivalent
 *    t2: The second type to be be equivalent
 *
 * Returns:
 *    None
 *
 * Raises:
 *    TypeError: Raised if the types cannot be unified.
 */
function unify($t1, $t2)
{
	$a = prune($t1);
	$b = prune($t2);
	if ($a instanceof TypeVariable) {
		if ($a != $b) {
			if (occursInType($a, $b))
				throw new TypeError("recursive unification");
			$a->instance = $b;
		}
	} else if (($a instanceof TypeOperator) and ($b instanceof TypeVariable)) {
		unify($b, $a);
	} else if (($a instanceof TypeOperator) and ($b instanceof TypeOperator)) {
		if ( ($a->name != $b->name) or (count($a->types) != count($b->types)))
			throw new TypeError("Type mismatch: ".(string)$a." != ".(string)$b);
 
		foreach( zip($a->types, $b->types) as $row) {
			unify($row[0], $row[1]);
		}
	} else {
		die("Not unified");
	}
}
 
 
/**
 * Returns the currently defining instance of t.
 *
 * As a side effect, collapses the list of type instances. The function Prune
 * is used whenever a type expression has to be inspected: it will always
 * return a type expression which is either an uninstantiated type variable or
 * a type operator; i.e. it will skip instantiated variables, and will
 * actually prune them from expressions to remove long chains of instantiated
 * variables.
 *
 * Args:
 *     t: The type to be pruned
 *
 * Returns:
 *     An uninstantiated TypeVariable or a TypeOperator
 */
function prune($t) {
	if ($t instanceof TypeVariable) {
		if ($t->instance !== null) {
			$t->instance = prune($t->instance);
			return  $t->instance;
		}
	}
	return $t;
}
 
 
/**
 * Checks whether a given variable occurs in a list of non-generic variables
 *
 * Note that a variables in such a list may be instantiated to a type term,
 * in which case the variables contained in the type term are considered
 * non-generic.
 *
 * Note: Must be called with v pre-pruned
 *
 * Args:
 *     v: The TypeVariable to be tested for genericity
 *     non_generic: A set of non-generic TypeVariables
 *
 * Returns:
 *     True if v is a generic variable, otherwise False
 */
function isGeneric($v, $non_generic) {
	return !(occursIn($v, $non_generic));
}
 
 
/**
 * Checks whether a type variable occurs in a type expression.
 *
 * Note: Must be called with v pre-pruned
 *
 * Args:
 *    v:  The TypeVariable to be tested for
 *    type2: The type in which to search
 *
 * Returns:
 *    True if v occurs in type2, otherwise False
 */
function occursInType($v, $type2) {
	$pruned_type2 = prune($type2);
	if ($pruned_type2 === $v)
		return true;
	else if ($pruned_type2 instanceof TypeOperator)
		return occursIn($v, $pruned_type2->types);
	return false;
}
 
 
/**
 * Checks whether a types variable occurs in any other types.
 *
 * Args:
 *     v:  The TypeVariable to be tested for
 *     types: The sequence of types in which to search
 *
 * Returns:
 *    True if t occurs in any of types, otherwise False
 */
function occursIn($t, $types) {
	foreach($types as $t2) {
		if (occursInType($t, $t2) === true) 
			return true;
	}
	return false;
}
 
 
 
//==================================================================#
// Example code to infrastructure above
 
 
/**
 * Try to evaluate a type printing the result or reporting errors.
 *
 * Args:
 *     env: The type environment in which to evaluate the expression.
 *    node: The root node of the abstract syntax tree of the expression.
 *
 * Returns:
 *     None
 */
function tryExp($env, $node) {
	print( (string) $node . " : ");
	try {
		$t = analyse($node, $env);
		print( (string) $t);
	} catch (ParseError $e) {
		print($e);
	} catch (TypeError $e) {
		print($e);
	}
}
 
 
$var1 = new TypeVariable();
$var2 = new TypeVariable();
$pair_type = new TypeOperator("*", array($var1, $var2));
 
$var3 = new TypeVariable();
 
$my_env = array(
		"pair" => new Func($var1, new Func($var2, $pair_type)),
		"true" => $Bool,
		"cond" => new Func($Bool, new Func($var3, new Func($var3, $var3))),
		"zero" => new Func($Integer, $Bool),
		"pred" => new Func($Integer, $Integer),
		"times"=> new Func($Integer, new Func($Integer, $Integer)),
		"concat" => new Func($String, new Func($String, $String))
);
 
$pair = new Apply(new Apply(new Ident("pair"), new Apply(new Ident("f"), new Ident("4"))), new Apply(new Ident("f"), new Ident("true")));
 
// This expression should pass
tryExp($my_env,
	new Letrec("factorial", # letrec factorial =
	new Lambda("n",    # fn n =>
	new Apply(
	new Apply(   # cond (zero n) 1
	new Apply(new Ident("cond"),     # cond (zero n)
	new Apply(new Ident("zero"), new Ident("n"))),
	new Ident("1")),
	new Apply(    # times n
	new Apply(new Ident("times"), new Ident("n")),
	new Apply(new Ident("factorial"),
	new Apply(new Ident("pred"), new Ident("n")))
	)
	)
	),      # in
	new Apply(new Ident("factorial"), new Ident("5"))
	)
);
 
echo "\n\n";
 
# This expression should fail
tryExp($my_env,
	# fn x => (pair(x(3) (x(true)))
	new Lambda("x",
		new Apply(
		new Apply(new Ident("pair"),
		new Apply(new Ident("x"), new Ident("3"))),
		new Apply(new Ident("x"), new Ident("true"))))
);
 
 
/* OUTPUT:
 
(letrec factorial = (fn n => (((cond (zero n)) 1) ((times n) (factorial (pred n))))) in (factorial 5)) : 
 
(fn x => ((pair (x 3)) (x true))) : Type mismatch: bool != int
 
*/
</pre>
<p><!-- <script src="https://gist.github.com/4667065.js?file=hindley_milner.php"></script> --></p>
]]></content:encoded>
			<wfw:commentRss>http://garrettbluma.com/2013/01/29/a-hindley-milner-type-system-in-php/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Synchronous Fan-In Pattern in Haskell</title>
		<link>http://garrettbluma.com/2012/12/03/a-synchronous-fan-in-pattern-in-haskell/</link>
		<comments>http://garrettbluma.com/2012/12/03/a-synchronous-fan-in-pattern-in-haskell/#comments</comments>
		<pubDate>Tue, 04 Dec 2012 01:30:31 +0000</pubDate>
		<dc:creator>Garrett Bluma</dc:creator>
				<category><![CDATA[Haskell]]></category>

		<guid isPermaLink="false">http://garrettbluma.com/?p=16812</guid>
		<description><![CDATA[Recently, I was in search of a good example of how a person could use Haskell's message passing system to build a fan-in pattern. That is, a pattern which takes multiple channels as inputs and watches each of them until a message is observed. In September, I spent a little time programming with Google's Go-language and really enjoyed this aspect of it. They handled this really well -- especially with the select keyword -- you can fan-in and pattern match at the same time, and timeouts are just handled as new channels with a particular message. But being a Haskell [...]]]></description>
			<content:encoded><![CDATA[<p>Recently, I was in search of a good example of how a person could use Haskell's message passing system to build a <em>fan-in pattern</em>. That is, a pattern which takes multiple channels as inputs and watches each of them until a message is observed. In September, I spent a little time programming with Google's Go-language and really enjoyed this aspect of it. They handled this really well -- especially with the <a href="http://golang.org/doc/effective_go.html#leaky_buffer">select</a> keyword -- you can fan-in and pattern match at the same time, and timeouts are just handled as new channels with a particular message.</p>
<p>But being a Haskell guy I thought this pattern would be more useful with strict-types. So, the following is a simple proof-of-concept of just that!</p>
<p>The following example depends on two packages: <a href="http://hackage.haskell.org/package/HTTP-4000.2.6">HTTP</a> and <a href="http://hackage.haskell.org/package/synchronous-channels">synchronous-channels</a>. </p>
<pre>
module Main where
 
import Control.Concurrent (forkIO, threadDelay)
import Control.Monad 
 
-- from package "HTTP"
import Network.HTTP
import Network.HTTP.Headers
import Network.HTTP.Base
 
-- from package "synchronous-channels"
import Control.Concurrent.Chan.Synchronous
 
-- takes a function, builds a channel, and returns the channel
async :: (Chan a -> IO ()) -> IO (Chan a)
async f = do
  x <- newChan
  forkIO $ f x
  return x
 
-- helper function to actually get the data
getURL :: [Char] -> Chan String -> IO ()
getURL x ch = do 
  putStrLn $ "requesting: " ++ x ++ "..."
  y <- simpleHTTP (getRequest x) 
  z <- return (getBody y)
  writeChan ch z
 
-- helper function to parse the response
getBody :: Either t (Response a) -> a
getBody (Right x) = rspBody x
 
-- the meat of the code. 
fanIn :: [Chan a] -> IO a 
fanIn cs = loop 
  where loop = do ready <- filterM hasData cs         -- check each channel for a message
                  case (take 1 ready) of              -- grab the first one with a message
                    [x] -> readChan x                 -- retrieve the message and return
                    [] -> loop                        -- (no message) keep looping
        hasData c = do _v <- tryPeekChan c            -- peek at the channel for data
                       return $ case _v of            -- observe the type of the result
                                  Success x -> True   -- (channel has a message) return true
                                  _         -> False  -- (channel has no messages) return false
 
-- apply the fan-in pattern once and return a result
collectFirst :: [Chan a] -> IO a
collectFirst cs = fanIn cs
 
-- apply the fan-in pattern in a loop and apply 'f' to each message
collectAll :: (b -> IO a) -> [Chan b] -> IO a
collectAll f cs = loop where loop = do { fanIn cs >>= f; loop }
 
main :: IO ()
main = do
    -- make four requests to the same place
    a <- async $ getURL "http://garrettbluma.com"
    b <- async $ getURL "http://garrettbluma.com"
    c <- async $ getURL "http://garrettbluma.com"
    d <- async $ getURL "http://garrettbluma.com"
    
    -- only use the first one that returns
    collectFirst [a,b,c,d] >>= print
 
    -- collectAll print [a,b,c,d,e,f,g,h]
    -- loops forever, printing all results
</pre>
<p><!-- <script src="https://gist.github.com/4199575.js?file=Channels.hs"></script> --></p>
]]></content:encoded>
			<wfw:commentRss>http://garrettbluma.com/2012/12/03/a-synchronous-fan-in-pattern-in-haskell/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Exhaustive Pattern-Matching in PHP</title>
		<link>http://garrettbluma.com/2012/10/05/exhaustive-pattern-matching-in-php/</link>
		<comments>http://garrettbluma.com/2012/10/05/exhaustive-pattern-matching-in-php/#comments</comments>
		<pubDate>Fri, 05 Oct 2012 16:09:32 +0000</pubDate>
		<dc:creator>Garrett Bluma</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Web Programming]]></category>

		<guid isPermaLink="false">http://garrettbluma.com/?p=16460</guid>
		<description><![CDATA[Modern functional languages have an amazing ability to verify program correctness at compile time. For this to happen, the compiler must be able to evaluate the usage of each programming language construct and determine its scope. Strong static types are a lifesaver here because it minimizes the search space. One particularly great feature of languages like Haskell, Scala, OCaml, and F# is that they are able to exhaustively check whether all conditions have been covered – This is usually called pattern matching. They do this by inspecting the types in use and checking whether each variation is handled. If a [...]]]></description>
			<content:encoded><![CDATA[<p>Modern functional languages have an amazing ability to verify program correctness at compile time. For this to happen, the compiler must be able to evaluate the usage of each programming language construct and determine its scope. Strong static types are a lifesaver here because it minimizes the search space.</p>
<p>One particularly great feature of languages like <a href="http://www.haskell.org/haskellwiki/Haskell">Haskell</a>, <a href="http://www.scala-lang.org/">Scala</a>, <a href="http://caml.inria.fr/">OCaml</a>, and <a href="http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/">F#</a> is that they are able to exhaustively check whether all conditions have been covered – This is usually called <em>pattern matching</em>. They do this by inspecting the types in use and checking whether each variation is handled. If a Boolean is detected with only a false condition handled, the compiler can come back and say “hey, you missed the condition for true.”</p>
<p>This may seem like a small feature that you can gloss over, but the truth is that SO many bugs… SO MANY… are caused by our simply not being aware of all the consequences. <em>Trust me</em> — or, better yet, do your own research.</p>
<p>Unfortunately, many of us are not able to use these smart compilers in our day-jobs (yet). I, for one, am still stuck in PHP for my day job. And although it may be near-impossible for us to get reliable static analysis in our interpreter, we can replicate some of this ability at run-time (at a cost).</p>
<p>The goal syntax is as follows:</p>
<pre>
var = match( search_term , enumerations ) 
      ->option( possible_term , function ) 
      ->option( possible_term , function ) 
      ->option( "_", function ) 
      ->exec();
</pre>
<p><!-- <script src="https://gist.github.com/3991490.js?file=figure1.php"></script> --></p>
<p>match should take in a search term and a set of possible options. These options would normally be inferred in a statically typed language, but we can cheat by supplying them manually. For numerical uses, this could be a range of numbers. For the example below, we will use an array of possible options. match() returns a closure which allows us to chain functions together.</p>
<p>possible_term is one of the terms we would like to match. When it is matched, the passed in function is evaluated and the value assigned to var.</p>
<p>“_”, also called <em>bottom</em>, is a catch all that we often see in functional languages. It matches <em>everything else</em> and effectively makes an exhaustiveness check useless. However, it is useful from time to time, therefore it is included here.</p>
<p>exec kicks off the search and evaluation process. It will check that the terms are included in the enumerations and that all of the enumerations are considered. As typical of PHP, if something goes wrong an Exception is thrown.</p>
<p>Normally we would see something like this. We match a status of “INIT” against a set of possible statuses.</p>
<pre>switch ("INIT") { 
    case "INIT": $msg = "program is initializing"; break; 
    case "END":  $msg = "program is ending"; break; 
}
</pre>
<p><!-- <script src="https://gist.github.com/3991490.js?file=figure2.php"></script> --></p>
<p>In the framework described above, this would look like this.</p>
<pre>$statuses = array("INIT","END"); 
$msg = match("INIT", $statuses) 
       ->option("INIT", function () { return "program is initializing"; } ) 
       ->option("END", function () { return "program is ending"; } ) 
       ->exec();
</pre>
<p><!-- <script src="https://gist.github.com/3991490.js?file=figure3.php"></script> --></p>
<p>These two are equivalent as-is, but what happens when we change this code to include a third status?</p>
<pre>$statuses = array("INIT","PROCESSING","END");</pre>
<p><!-- <script src="https://gist.github.com/3991490.js?file=figure4.php"></script> --></p>
<p>If we try to run with the switch statement, we find that the condition is not caught and the program continues on blissfully unaware. In the second option, we actually catch the problem.</p>
<p>Score one point for the pedantic programmers! We go back to our code, add a clause for “PROCESSING” and then continue.</p>
<pre>
$msg = match("INIT", $statuses) 
       ->option("INIT", function () { return "program is initializing"; } ) 
       ->option("PROCESSING", function() { return "program is running"; } ) 
       ->option("END", function () { return "program is ending"; } ) 
       ->exec(); 
 
// => No Errors
</pre>
<p><!-- <script src="https://gist.github.com/3991490.js?file=figure5.php"></script> --></p>
<p>Now, this sounds nice and all, but there is an evil underbelly of this implementation. The performance. It’s terrible. 40x slower than the switch statement I gave above. This is because the runtime has to loop through each case, checking for completeness, and passing closures around like it’s going out of style. I’m sure the implementation can be improved, but here is the current benchmark over 100,000 iterations.</p>
<div style="text-align: center">
<div class="dropshadow">
<img src="https://s3.amazonaws.com/gbluma-public/images/pattern-matching-performance.png" alt="Pattern Matching Performance" />
</div>
</div>
<p><br></p>
<p>Regardless of performance, this is an interesting thought experiment. It is nice to have some guarantees in a reckless environment like PHP, but I would be cautious to use this in production — and even then, only sparingly.</p>
<h2 id="full-code">Full Code</h2>
<pre>
&lt;?php 
 
class Matcher {
    private $cases = array(); 
 
    function __construct($target, $source) { 
        $this->target = $target; 
        $this->source = $source; 
    } 
 
    public function option($p,$f) { 
        $this->cases[$p] = $f; 
        return $this; 
    } 
 
    public function exec() { 
        // check that element is in search set 
        if (!isset($this->cases[$this->target])) { 
            // do we have a catch-all? 
            if (isset($this->cases['_'])) { 
                // ... yes, use catch all. 
                return $this->cases["_"](); 
            } else { 
                // ... no, throw error. 
                throw new Exception("Search term not found."); 
            } 
        } 
        if (!isset($this->cases['_'])) { 
            // check for exhaustive matching 
            foreach($this->source as &$s) { 
                if (!isset($this->cases[$s])) { 
                    throw new Exception("$s option not covered" 
                        . " in exhaustive pattern match"); 
                } 
            } 
        }
 
        // we can assume that we have a match return 
        $this->cases[$this->target](); 
    } 
} 
 
// convenience function to simplify implementation 
function match($target, $source) { 
    $o = new Matcher($target, $source); 
    return $o; 
}
</pre>
<p><!-- <script src="https://gist.github.com/3991490.js?file=Matcher.php"></script> --></p>
<h2 id="example-usage">Example Usage</h2>
<pre>
&lt;?php 
 
// normally we would see something like this. 
switch ("INIT") { 
    case "INIT": $msg = "program is initializing"; break; 
    case "END":  $msg = "program is ending"; break; 
} 
 
/*
 * The problem with this is that we don't know when something is legitimately
 * broken. We assume that any unknown status can be ignored. This is bad.
 */ 
$statuses = array("INIT","END"); 
$msg = match("INIT", $statuses) 
       ->option("INIT", function () { return "program is initializing"; } ) 
       ->option("END", function () { return "program is ending"; } ) 
       ->exec();
</pre>
<p><!-- <script src="https://gist.github.com/3991490.js?file=usage.php"></script> --></p>
]]></content:encoded>
			<wfw:commentRss>http://garrettbluma.com/2012/10/05/exhaustive-pattern-matching-in-php/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>FFI in Idris &#8211; A Basic Example</title>
		<link>http://garrettbluma.com/2012/10/03/ffi-idris-1/</link>
		<comments>http://garrettbluma.com/2012/10/03/ffi-idris-1/#comments</comments>
		<pubDate>Thu, 04 Oct 2012 01:48:29 +0000</pubDate>
		<dc:creator>Garrett Bluma</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://garrettbluma.com/?p=16435</guid>
		<description><![CDATA[Idris is a dependent-typed language that offers a lot of great features &#8212; most of which I won't talk about right now! What I will explain, quickly, is an easy example of using Idris' foreign function interface (ffi). The FFI system in Idris is very similar to that of Haskell, but obviously it is tailored to the system it lives in. I searched for an easy example of how to to use it, but I didn't find much luck. Here is a really basic FFI call that uses C to multiply two numbers. mylib.c #include &#60;stdio.h&#62; void myMult(int x, int [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://idris-lang.org/" title="Idris">Idris</a> is a <a href="http://en.wikipedia.org/wiki/Dependent_type">dependent-typed</a> language that offers a lot of great features &mdash; most of which I won't talk about right now! What I <em>will</em> explain, quickly, is an easy example of using Idris' <a href="http://en.wikipedia.org/wiki/Foreign_function_interface">foreign function interface</a> (ffi).</p>
<p>The FFI system in Idris is very similar to that of Haskell, but obviously it is tailored to the system it lives in. I searched for an easy example of how to to use it, but I didn't find much luck.</p>
<p>Here is a really basic FFI call that uses C to multiply two numbers.</p>
<h4 id="mylib.c">mylib.c</h4>
<pre><code>#include &lt;stdio.h&gt; 
void myMult(int x, int y) { 
    printf("%d\n", x * y); 
}</code></pre>
<h4 id="mylib.h">mylib.h</h4>
<pre><code>#include &lt;stdio.h&gt; 
void myMult(int x, int y);</code></pre>
<h4 id="main.idr">main.idr</h4>
<pre><code>module main 

%include "mylib.h" 
%link "mylib.o" 

myMult     : Int -&gt; Int -&gt; IO () 
myMult x y = mkForeign (FFun "myMult" [FInt, FInt] FUnit) x y 

main : IO () 
main = do 
  myMult 5 4</code></pre>
<h4 id="how-to-build">How to build</h4>
<pre><code>$ gcc -c mylib.c -o mylib.o 
$ idris main.idr -o main 
$ ./main 
    20</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://garrettbluma.com/2012/10/03/ffi-idris-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Monitoring multicore CPU info in Linux</title>
		<link>http://garrettbluma.com/2012/09/07/monitoring-multicore-cpu-info-in-linux/</link>
		<comments>http://garrettbluma.com/2012/09/07/monitoring-multicore-cpu-info-in-linux/#comments</comments>
		<pubDate>Fri, 07 Sep 2012 20:53:56 +0000</pubDate>
		<dc:creator>Garrett Bluma</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://garrettbluma.com/?p=15073</guid>
		<description><![CDATA[If you are running in Ubuntu Linux <tt>mpstat</tt> is a useful program to track CPU performance. It can display usage information about each of your running cores.]]></description>
			<content:encoded><![CDATA[<p>If you are running in Ubuntu Linux <tt>mpstat</tt> is a useful program to track CPU performance. It can display usage information about each of your running cores.</p>
<p>You can install it using the following command:</p>
<pre>sudo apt-get install sysstat</pre>
<p>Once installed you can run a bash script to record CPU info. In this case I'm logging 10 times a second. This will block until you press Control-C to kill the logging. (Also, consider removing the sleep 0.1; for better data.)</p>
<pre>while x=0; do mpstat -P ALL >> cpu_log.txt; sleep 0.1; done</pre>
<p>In another terminal you can fire off your program (or ANY program) and see track the performance data. The output looks like this:</p>
<pre>03:21:08 PM  CPU    %usr   %nice    %sys %iowait    %irq   %soft  %steal  %guest   %idle
03:21:08 PM  all    0.37    0.00    0.33    0.50    0.00    0.02    0.00    0.00   98.78
03:21:08 PM    0    0.51    0.00    0.45    0.57    0.00    0.03    0.00    0.00   98.43
03:21:08 PM    1    0.29    0.00    0.26    0.45    0.00    0.01    0.00    0.00   99.00</pre>
<p>The output shows performance information for cores 0 and 1, as well as a average that summarizes overall performance.</p>
]]></content:encoded>
			<wfw:commentRss>http://garrettbluma.com/2012/09/07/monitoring-multicore-cpu-info-in-linux/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
