<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Attractive Chaos &#187; benchmark</title>
	<atom:link href="http://attractivechaos.wordpress.com/tag/benchmark/feed/" rel="self" type="application/rss+xml" />
	<link>http://attractivechaos.wordpress.com</link>
	<description>Just another WordPress.com weblog</description>
	<lastBuildDate>Tue, 29 Sep 2009 22:22:13 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='attractivechaos.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/3aaf4ad34bfdf87dcbb70d9e3cbd326d?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>Attractive Chaos &#187; benchmark</title>
		<link>http://attractivechaos.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://attractivechaos.wordpress.com/osd.xml" title="Attractive Chaos" />
		<item>
		<title>Another Look at my old Benchmark</title>
		<link>http://attractivechaos.wordpress.com/2008/10/07/another-look-at-my-old-benchmark/</link>
		<comments>http://attractivechaos.wordpress.com/2008/10/07/another-look-at-my-old-benchmark/#comments</comments>
		<pubDate>Tue, 07 Oct 2008 12:02:47 +0000</pubDate>
		<dc:creator>attractivechaos</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[benchmark]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[cpp]]></category>
		<category><![CDATA[myprog]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://attractivechaos.wordpress.com/?p=586</guid>
		<description><![CDATA[This is a follow-up of my previous post. Here I change the table to several charts. Hope it seems more friendly to readers. You can find the links to these libraries in that table. Their source codes, including my testing code, are available here. You may also want to see my previous posts in the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=attractivechaos.wordpress.com&blog=4545823&post=586&subd=attractivechaos&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>This is a follow-up of my previous post. Here I change <a href="http://attractivechaos.awardspace.com/udb.html">the table</a> to several charts. Hope it seems more friendly to readers. You can find the links to these libraries in that table. Their source codes, including my testing code, are available <a href="http://attractivechaos.awardspace.com/download/udb-latest.tar.bz2">here</a>. You may also want to see my previous posts in the last few days for my interpretation to the results.</p>
<p>On C string (char*) keys, I fail to use JE_rb_old and JE_rb_new to get the correct result on Mac and so they are not showed in the charts. I would really appreciate if someone may give me the correct implementation using these libraries. In addition, tr1_unordered_map uses a lot of memory according to my program. The memory for string keys are faked.</p>
<p>For conveniece, here are some brief descriptions of these libraries (with no order):</p>
<ul>
<li>google_dense and google_sparse: <a href="http://code.google.com/p/google-sparsehash/">google&#8217;s sparsehash library</a>. Google_dense is fast but memory hungery while google_sparse is the opposite.</li>
<li>sgi_hash_map and sgi_map: <a href="http://www.sgi.com/tech/stl/">SGI&#8217;s STL</a> that comes with g++-4. The backend of sgi_map is a three-pointer red-black tree.</li>
<li>tr1::unordered_map: GCC&#8217;s TR1 library that comes with g++-4. It implements a hash table.</li>
<li>rdestl::hash_map: from <a href="http://code.google.com/p/rdestl/">RDESTL</a>, another implementation of STL.</li>
<li><a href="http://uthash.sourceforge.net/">uthash</a>: a hash library in C</li>
<li>JG_btree: <a href="http://resnet.uoregon.edu/~gurney_j/jmpc/btree.html">John-Mark Gurney&#8217;s btree library</a>.</li>
<li>JE_rb_new, JE_rb_old, JE_trp_hash and JE_trp_prng: <a href="http://www.canonware.com/~ttt/2008/07/treaps-versus-red-black-trees.html">Jason Evans&#8217; binary search tree libraries</a>. JE_rb_new implements a left-leaning red-black tree; JE_rb_old a three-pointer red-black tree; both JE_trp_hash and JE_trp_prng implement treaps but with different strategies on randomness.</li>
<li>libavl_rb, libavl_prb, libavl_avl and libavl_bst: from <a href="http://www.stanford.edu/~blp/avl/">GNU libavl</a>. They implment a two-pointer red-black tree, a three-pointer red-black tree, an AVL tree and a unbalanced binary search tree, respectively.</li>
<li>NP_rbtree and NP_splaytree: <a href="http://www.freebsd.org/cgi/cvsweb.cgi/src/sys/sys/tree.h">Niels Provos&#8217; tree library</a> for FreeBSD. A three-pointer red-black tree and a splay tree.</li>
<li>TN_rbtree: <a href="http://www.darkridge.com/~jpr5/archive/alg/node21.html">Thomas Niemann&#8217;s red-black tree</a>. I ported it to C++.</li>
<li>sglib_rbtree: from <a href="http://sglib.sourceforge.net/">SGLIB</a>. It implements a two-pointer recursive red-black tree (all the other binary search trees are implemented without recursion).</li>
<li>libavl_avl_cpp, libavl_rb_cpp and libavl_rb_cpp2: incomplete C++ version of libavl (no iterator), ported by me. Libavl_rb_cpp2 further uses the same technique in JE_rb_new to save the color bit. Source codes available in the package.</li>
<li><a href="http://attractivechaos.awardspace.com/khash.h.html">khash</a> and <a href="http://attractivechaos.awardspace.com/kbtree.h.html">kbtree</a>: my hash table and B-tree implementation. kbtree is based on JG_rbtree.</li>
</ul>
<p><a href="http://klib.sourceforge.net/images/udb-int-cpu.png"><img class="alignnone size-full wp-image-622" title="udb-int-cpu" src="http://klib.sourceforge.net/images/udb-int-cpu.png" alt="" width="542" height="309" /></a></p>
<p><a href="http://klib.sourceforge.net/images/udb-int-mem.png"><img class="alignnone size-full wp-image-623" title="udb-int-mem" src="http://klib.sourceforge.net/images/udb-int-mem.png" alt="" width="542" height="309" /></a></p>
<p><a href="http://klib.sourceforge.net/images/udb-str-cpu.png"><img class="alignnone size-full wp-image-624" title="udb-str-cpu" src="http://klib.sourceforge.net/images/udb-str-cpu.png" alt="" width="542" height="308" /></a></p>
<p><a href="http://attractivechaos.files.wordpress.com/2008/10/udb-str-mem.png"><img class="alignnone size-full wp-image-625" title="udb-str-mem" src="http://klib.sourceforge.net/images/udb-str-mem.png" alt="" width="543" height="309" /></a></p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/attractivechaos.wordpress.com/586/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/attractivechaos.wordpress.com/586/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/attractivechaos.wordpress.com/586/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/attractivechaos.wordpress.com/586/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/attractivechaos.wordpress.com/586/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/attractivechaos.wordpress.com/586/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/attractivechaos.wordpress.com/586/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/attractivechaos.wordpress.com/586/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/attractivechaos.wordpress.com/586/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/attractivechaos.wordpress.com/586/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=attractivechaos.wordpress.com&blog=4545823&post=586&subd=attractivechaos&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://attractivechaos.wordpress.com/2008/10/07/another-look-at-my-old-benchmark/feed/</wfw:commentRss>
		<slash:comments>24</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/047ebc7bb9ff37a0da844413856e92cb?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">attractivechaos</media:title>
		</media:content>

		<media:content url="http://klib.sourceforge.net/images/udb-int-cpu.png" medium="image">
			<media:title type="html">udb-int-cpu</media:title>
		</media:content>

		<media:content url="http://klib.sourceforge.net/images/udb-int-mem.png" medium="image">
			<media:title type="html">udb-int-mem</media:title>
		</media:content>

		<media:content url="http://klib.sourceforge.net/images/udb-str-cpu.png" medium="image">
			<media:title type="html">udb-str-cpu</media:title>
		</media:content>

		<media:content url="http://klib.sourceforge.net/images/udb-str-mem.png" medium="image">
			<media:title type="html">udb-str-mem</media:title>
		</media:content>
	</item>
		<item>
		<title>Is There an Overhead to Retrieve an Element in a Struct?</title>
		<link>http://attractivechaos.wordpress.com/2008/10/01/is-there-an-overhead-to-retrieve-an-element-in-a-struct/</link>
		<comments>http://attractivechaos.wordpress.com/2008/10/01/is-there-an-overhead-to-retrieve-an-element-in-a-struct/#comments</comments>
		<pubDate>Wed, 01 Oct 2008 20:47:33 +0000</pubDate>
		<dc:creator>attractivechaos</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[benchmark]]></category>
		<category><![CDATA[C]]></category>

		<guid isPermaLink="false">http://attractivechaos.wordpress.com/?p=541</guid>
		<description><![CDATA[I was wondering whether retrieving an element in a struct will incur additional overhead. And so I did the following experiment. Here the same array is sorted in two ways: with or without data retrieving from a struct. Both ways yield identical results. The question is whether the compiler knows the two ways are the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=attractivechaos.wordpress.com&blog=4545823&post=541&subd=attractivechaos&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>I was wondering whether retrieving an element in a struct will incur additional overhead. And so I did the following experiment. Here the same array is sorted in two ways: with or without data retrieving from a struct. Both ways yield identical results. The question is whether the compiler knows the two ways are the same and can achieve the same efficiency.</p>
<p>#include <time.h><br />
#include <stdlib.h><br />
#include <stdio.h><br />
#include &#8220;ksort.h&#8221;</p>
<p>typedef struct {<br />
	int a;<br />
} myint_t;</p>
<p>#define myint_lt(_a, _b) ((_a).a < (_b).a)</p>
<p>KSORT_INIT_GENERIC(int)<br />
KSORT_INIT(my, myint_t, myint_lt)</p>
<p>int main()<br />
{<br />
	int i, N = 10000000;<br />
	myint_t *a;<br />
	clock_t t;<br />
	a = (myint_t*)malloc(sizeof(myint_t) * N);<br />
	srand48(11);<br />
	for (i = 0; i != N; ++i) a[i].a = lrand48();<br />
	t = clock();<br />
	ks_introsort(int, N, (int*)a);<br />
	printf(&#8220;%.3lf\n&#8221;, (double)(clock() &#8211; t) / CLOCKS_PER_SEC);<br />
	srand48(11);<br />
	for (i = 0; i != N; ++i) a[i].a = lrand48();<br />
	t = clock();<br />
	ks_introsort(my, N, a);<br />
	printf(&#8220;%.3lf\n&#8221;, (double)(clock() &#8211; t) / CLOCKS_PER_SEC);<br />
	free(a);<br />
	return 0;<br />
}</p>
<p>Here is the speed with different compilers on different CPUs (first value for without data retrieving and second with):</p>
<ul>
<li>Mac-Intel, gcc-4.0, -O2: 1.422 sec vs. 1.802 sec</li>
<li>Mac-Intel, gcc-4.2, -O2: 1.438 vs. 1.567</li>
<li>Mac-Intel, gcc-4.0, -O2 -fomit-frame-pointer: 1.425 vs. 1.675</li>
<li>Mac-Intel, gcc-4.2, -O2 -fomit-frame-pointer: 1.438 vs. 1.448</li>
<li>Linux-Intel, gcc-4.1, -O2: 1.600 vs. 1.520</li>
<li>Linux-Intel, gcc-4.1, -O2 -fomit-frame-pointer: 1.620 vs. 1.530</li>
<li>Linux-Intel, icc, -O2 -fomit-frame-pointer: 1.600 vs. 1.580</li>
</ul>
<p>The conclusion is retrieving data from a struct may have marginal overhead in comprison to direct data access. However, a good compiler can avoid this and produce nearly optimal machine code. Using &#8220;-fomit-frame-pointer&#8221; may help for some machines, but not for others. In addition, it is a bit surprising to me that gcc-linux generates faster code for data retrieval in a struct. Swapping the two ways does not change the conclusion.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/attractivechaos.wordpress.com/541/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/attractivechaos.wordpress.com/541/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/attractivechaos.wordpress.com/541/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/attractivechaos.wordpress.com/541/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/attractivechaos.wordpress.com/541/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/attractivechaos.wordpress.com/541/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/attractivechaos.wordpress.com/541/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/attractivechaos.wordpress.com/541/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/attractivechaos.wordpress.com/541/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/attractivechaos.wordpress.com/541/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=attractivechaos.wordpress.com&blog=4545823&post=541&subd=attractivechaos&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://attractivechaos.wordpress.com/2008/10/01/is-there-an-overhead-to-retrieve-an-element-in-a-struct/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/047ebc7bb9ff37a0da844413856e92cb?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">attractivechaos</media:title>
		</media:content>
	</item>
		<item>
		<title>Futher Discussion on Search Trees</title>
		<link>http://attractivechaos.wordpress.com/2008/09/28/futher-discussion-on-search-trees/</link>
		<comments>http://attractivechaos.wordpress.com/2008/09/28/futher-discussion-on-search-trees/#comments</comments>
		<pubDate>Sun, 28 Sep 2008 21:23:28 +0000</pubDate>
		<dc:creator>attractivechaos</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[benchmark]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[cpp]]></category>
		<category><![CDATA[myprog]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://attractivechaos.wordpress.com/?p=535</guid>
		<description><![CDATA[Over the weekend, I have done a more comprehensive benchmark of various libraries on search trees. Two AVL, seven red-black tree, one Splay tree, two treap implementations are involved, together with seven hash table libraries. As I need to present a big table, I have to write it in a free-style HTML page. You can [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=attractivechaos.wordpress.com&blog=4545823&post=535&subd=attractivechaos&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Over the weekend, I have done a more comprehensive benchmark of various libraries on search trees. Two AVL, seven red-black tree, one Splay tree, two treap implementations are involved, together with seven hash table libraries. As I need to present a big table, I have to write it in a free-style HTML page. You can find the complete benchmark <a href="http://attractivechaos.awardspace.com/udb.html">here</a> and all the source codes <a href="http://attractivechaos.awardspace.com/download/udb-20080928.tar.bz2">here</a>. I only copy the &#8220;concluding remarks&#8221; in the benchmark page as follows:</p>
<ul>
<li>Hash table is preferred over search trees if we do not require order.</li>
<li>In applications similar to my example, B-tree is better than most of binary search trees in terms of both speed and memory.</li>
<li>AVL tree and red-black tree are the best general-purposed BSTs. They are very close in efficiency.</li>
<li>For pure C libraries, using macros is usually more efficient than using void* to achieve generic programming.</li>
</ul>
<p>You can find the result and much more discussions in <a href="http://attractivechaos.awardspace.com/udb.html">that page</a>. If you think the source codes or the design of benchmark can be improved, please leave comments here or send me E-mail. In addition, I failed to use several libraries and so you can see some blank in the table. I would also appreciate if someone could show me how to use those libraries correctly.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/attractivechaos.wordpress.com/535/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/attractivechaos.wordpress.com/535/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/attractivechaos.wordpress.com/535/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/attractivechaos.wordpress.com/535/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/attractivechaos.wordpress.com/535/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/attractivechaos.wordpress.com/535/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/attractivechaos.wordpress.com/535/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/attractivechaos.wordpress.com/535/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/attractivechaos.wordpress.com/535/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/attractivechaos.wordpress.com/535/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=attractivechaos.wordpress.com&blog=4545823&post=535&subd=attractivechaos&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://attractivechaos.wordpress.com/2008/09/28/futher-discussion-on-search-trees/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/047ebc7bb9ff37a0da844413856e92cb?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">attractivechaos</media:title>
		</media:content>
	</item>
		<item>
		<title>C Array vs. C++ Vector</title>
		<link>http://attractivechaos.wordpress.com/2008/09/19/c-array-vs-c-vector/</link>
		<comments>http://attractivechaos.wordpress.com/2008/09/19/c-array-vs-c-vector/#comments</comments>
		<pubDate>Fri, 19 Sep 2008 08:03:34 +0000</pubDate>
		<dc:creator>attractivechaos</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[benchmark]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[cpp]]></category>

		<guid isPermaLink="false">http://attractivechaos.wordpress.com/?p=456</guid>
		<description><![CDATA[Here is a piece of source codes that compare C arrays and C++ vectors. It tests six scenarios: a) preallocated C array; b) dynamically growing C array; c) dynamical C vector calling kv_a macro (in my kvec.h); d) dynamical C vector calling kv_push macro (in my kvec.h); e) preallocated C++ vector and f) dynamically growing C++ [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=attractivechaos.wordpress.com&blog=4545823&post=456&subd=attractivechaos&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Here is a piece of source codes that compare C arrays and C++ vectors. It tests six scenarios: a) preallocated C array; b) dynamically growing C array; c) dynamical C vector calling kv_a macro (in my kvec.h); d) dynamical C vector calling kv_push macro (in my kvec.h); e) preallocated C++ vector and f) dynamically growing C++ vector. You can find my kvec.h on my blog.</p>
<pre class="brush: cpp;">
#include &lt;vector&gt;
#include &lt;time.h&gt;
#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &quot;kvec.h&quot;

int main()
{
	int M = 10, N = 20000000, i, j;
	clock_t t;
	t = clock();
	for (i = 0; i &lt; M; ++i) {
		int *array = (int*)malloc(N * sizeof(int));
		for (j = 0; j &lt; N; ++j) array[j] = j;
		free(array);
	}
	printf(&quot;C array, preallocated: %.3f sec\n&quot;,
		   (float)(clock() - t) / CLOCKS_PER_SEC);
	t = clock();
	for (i = 0; i &lt; M; ++i) {
		int *array = 0, max = 0;
		for (j = 0; j &lt; N; ++j) {
			if (j == max) {
				max = !max? 1 : max &lt;&lt; 1;
				array = (int*)realloc(array, sizeof(int)*max);
			}
			array[j] = j;
		}
		free(array);
	}
	printf(&quot;C array, dynamic: %.3f sec\n&quot;,
		   (float)(clock() - t) / CLOCKS_PER_SEC);
	t = clock();
	for (i = 0; i &lt; M; ++i) {
		kvec_t(int) array;
		kv_init(array);
		kv_resize(int, array, N);
		for (j = 0; j &lt; N; ++j) kv_a(int, array, j) = j;
		kv_destroy(array);
	}
	printf(&quot;C vector, dynamic (kv_a): %.3f sec\n&quot;,
		   (float)(clock() - t) / CLOCKS_PER_SEC);
	t = clock();
	for (i = 0; i &lt; M; ++i) {
		kvec_t(int) array;
		kv_init(array);
		for (j = 0; j &lt; N; ++j)
			kv_push(int, array, j);
		kv_destroy(array);
	}
	printf(&quot;C vector, dynamic (kv_push): %.3f sec\n&quot;,
		   (float)(clock() - t) / CLOCKS_PER_SEC);
	t = clock();
	for (i = 0; i &lt; M; ++i) {
		std::vector&lt;int&gt; array;
		array.reserve(N);
		for (j = 0; j &lt; N; ++j) array[j] = j;
	}
	printf(&quot;C++ vector, preallocated: %.3f sec\n&quot;,
		   (float)(clock() - t) / CLOCKS_PER_SEC);
	t = clock();
	for (i = 0; i &lt; M; ++i) {
		std::vector&lt;int&gt; array;
		for (j = 0; j &lt; N; ++j) array.push_back(j);
	}
	printf(&quot;C++ vector, dynamic: %.3f sec\n&quot;,
		   (float)(clock() - t) / CLOCKS_PER_SEC);
	return 0;
}
</pre>
<p>Here is the result on two machines (compiled with g++ -O2 -fomit-frame-pointer -finline-functions):</p>
<table border="1" cellspacing="0" cellpadding="0" align="center">
<tbody>
<tr>
<td>type</td>
<td>MacIntel</td>
<td>LinuxIntel</td>
</tr>
<tr>
<td>C array, preallocated</td>
<td>1.589</td>
<td>1.180</td>
</tr>
<tr>
<td>C array, dynamic</td>
<td>2.064</td>
<td>1.340</td>
</tr>
<tr>
<td>C vector, dynamic (kv_a)</td>
<td>2.051</td>
<td>1.600</td>
</tr>
<tr>
<td>C vector, dynamic (kv_push)</td>
<td>1.932</td>
<td>1.250</td>
</tr>
<tr>
<td>C++ vector, preallocated</td>
<td>2.119</td>
<td>1.590</td>
</tr>
<tr>
<td>C++ vector, dynamic</td>
<td>5.095</td>
<td>3.770</td>
</tr>
</tbody>
</table>
<p>Such result may vary with different machines/compilers, but not much.</p>
<p><strong>Update:</strong> My example passed valgrind check on a Linux (Debian etch, g++-4.1), but Tom_ pointed out that it did not pass VC++&#8217;s debugger as vector::operator[] writes outside vector::size(). Anyway, it is good not to use operator[] in my way. You can replace reserve()+[] with resize()+[] or reserve()+push_back(). On my machine, the replacement gives a little bit slower speed, but it is safer/more portable in that way. Thanks for all the comments.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/attractivechaos.wordpress.com/456/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/attractivechaos.wordpress.com/456/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/attractivechaos.wordpress.com/456/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/attractivechaos.wordpress.com/456/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/attractivechaos.wordpress.com/456/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/attractivechaos.wordpress.com/456/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/attractivechaos.wordpress.com/456/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/attractivechaos.wordpress.com/456/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/attractivechaos.wordpress.com/456/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/attractivechaos.wordpress.com/456/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=attractivechaos.wordpress.com&blog=4545823&post=456&subd=attractivechaos&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://attractivechaos.wordpress.com/2008/09/19/c-array-vs-c-vector/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/047ebc7bb9ff37a0da844413856e92cb?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">attractivechaos</media:title>
		</media:content>
	</item>
		<item>
		<title>Comparison of Hash Table Libraries</title>
		<link>http://attractivechaos.wordpress.com/2008/08/28/comparison-of-hash-table-libraries/</link>
		<comments>http://attractivechaos.wordpress.com/2008/08/28/comparison-of-hash-table-libraries/#comments</comments>
		<pubDate>Thu, 28 Aug 2008 22:22:54 +0000</pubDate>
		<dc:creator>attractivechaos</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[benchmark]]></category>
		<category><![CDATA[C]]></category>
		<category><![CDATA[cpp]]></category>
		<category><![CDATA[hash]]></category>
		<category><![CDATA[myprog]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://attractivechaos.wordpress.com/?p=278</guid>
		<description><![CDATA[As a Perl programmer, I enjoy a lot using hash tables. I keep this habit in C/C++ programming. Then what C/C++ hash libraries are available? How are they compared to each other? In this post, I will give a brief review of hash libraries and present a small benchmark showing their practical performance.
Hash table libraries
In [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=attractivechaos.wordpress.com&blog=4545823&post=278&subd=attractivechaos&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>As a Perl programmer, I enjoy a lot using hash tables. I keep this habit in C/C++ programming. Then what C/C++ hash libraries are available? How are they compared to each other? In this post, I will give a brief review of hash libraries and present a small benchmark showing their practical performance.</p>
<p><strong>Hash table libraries</strong></p>
<p>In C++, the most widely used hash table implementation is hash_map/set in <a href="http://www.sgi.com/tech/stl/">SGI STL</a>, which is part of the GCC compiler. Note that hash_map/set is SGI&#8217;s extention to STL, but is not part of STL. TR1 (<a href="http://en.wikipedia.org/wiki/Technical_Report_1">technical report 1</a>) tries to standardize hash tables. It provides unordered_map/set with similar API to hash_map/set. Most of TR1 routines are available since gcc-4.0. <a href="http://code.google.com/p/google-sparsehash/">Google sparse hash</a> is another C++ hash table template library with similar API to hash_map/set. It provides two implementations, one is efficient in speed and the other is in memory.</p>
<p>In contrast, there are few good C libraries around. I have tried <a href="http://www.sunrisetel.net/software/devtools/sunrise-data-dictionary.shtml">SunriseDD</a>, <a href="http://uthash.sourceforge.net/">uthash</a>, <a href="http://linux.die.net/man/3/hsearch">glibc hash table</a>, <a href="http://freshmeat.net/projects/hashit/">hashit</a>, Christopher Clark&#8217;s <a href="http://www.cl.cam.ac.uk/~cwc22/hashtable/">hashtable</a>, <a href="http://www.gtk.org/">glib hash table</a> and <a href="http://www.ipd.bth.se/ska/sim_home/libghthash.html">ghthash</a>. SunriseDD sounds a great library that implements a lock-free hash table. However, I am not sure how to install it or use it, although the code itself is well documented. Uthash is a single header file. It is quite complex to use and incompatiable with C++. It also lacks basic APIs such as counting how many elements in the hash table. Glibc hash and hashit seem to only implement static hash tables. Glibc hash even does not have deletion operation. Only glib hash, CC&#8217;s hashtable and ghthash implement most of common operations. And they still have their weakness in comparison to C++ implementations (see below).</p>
<p><strong>D</strong><strong>esign of the benchmark</strong></p>
<p>The benchmark is comprised of two experiments. In the first experiment, a random integer array of 5 million elements is generated with about 1.25 million distinct keys. Each element is then tested whether it is present in the hash. If the element is in the hash, it will be removed; otherwise, it will be inserted. 625,792 distinct keys will be in the hash after this process. To test performance on string input, I convert integers to strings with sprintf().</p>
<p>The second experiment is designed by Craig Silverstein, the author of sparsehash. I am using his source codes. This experiment tests the performance of insertion from zero sized hash, insertion from preallocated hash, replacement, query, query of empty hash, and removal.</p>
<p><strong>Results</strong></p>
<p>The following table gives the results in the first experiment:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="90">Library</td>
<td>Mac-intCPU (sec)</td>
<td>Mac-strCPU (sec)</td>
<td>Mac PeakMem (MB)</td>
<td>Linux-intCPU (sec)</td>
<td>Linux-strCPU (sec)</td>
<td>Linux PeakMem (MB)</td>
</tr>
<tr>
<td>glib</td>
<td>1.904</td>
<td>2.436</td>
<td>11.192</td>
<td>3.490</td>
<td>4.720</td>
<td>24.968</td>
</tr>
<tr>
<td>ghthash</td>
<td>2.593</td>
<td>2.869</td>
<td>29.0/39.0</td>
<td>3.260</td>
<td>3.460</td>
<td>61.232</td>
</tr>
<tr>
<td>CC&#8217;s hashtable</td>
<td>2.740</td>
<td>3.424</td>
<td>59.756</td>
<td>3.040</td>
<td>4.050</td>
<td>129.020</td>
</tr>
<tr>
<td>TR1</td>
<td>1.371</td>
<td>2.571</td>
<td>16.140</td>
<td>1.750</td>
<td>3.300</td>
<td>28.648</td>
</tr>
<tr>
<td>STL hash_set</td>
<td>1.631</td>
<td>2.698</td>
<td>14.592</td>
<td>2.070</td>
<td>3.430</td>
<td>25.764</td>
</tr>
<tr>
<td>google-sparse</td>
<td>2.957</td>
<td>6.098</td>
<td>4.800</td>
<td>2.560</td>
<td>6.930</td>
<td>5.42/8.54</td>
</tr>
<tr>
<td>google-dense</td>
<td>0.700</td>
<td>2.833</td>
<td>24.616</td>
<td>0.550</td>
<td>2.820</td>
<td>24.7/49.3</td>
</tr>
<tr>
<td>khash (C++)</td>
<td>1.089</td>
<td>2.372</td>
<td>6.772</td>
<td>1.100</td>
<td>2.900</td>
<td>6.88/13.1</td>
</tr>
<tr>
<td>khash (C)</td>
<td>0.987</td>
<td>2.294</td>
<td>6.780</td>
<td>1.140</td>
<td>2.940</td>
<td>6.91/13.1</td>
</tr>
<tr>
<td>STL set (RB)</td>
<td>5.898</td>
<td>12.978</td>
<td>19.868</td>
<td>7.840</td>
<td>18.620</td>
<td>29.388</td>
</tr>
<tr>
<td>kbtree (C)</td>
<td>3.080</td>
<td>13.413</td>
<td>3.268</td>
<td>4.260</td>
<td>17.620</td>
<td>4.86/9.59</td>
</tr>
<tr>
<td>NP&#8217;s splaytree</td>
<td>8.455</td>
<td>23.369</td>
<td>8.936</td>
<td>11.180</td>
<td>27.610</td>
<td>19.024</td>
</tr>
</tbody>
</table>
<p>Notes:</p>
<ul>
<li>Please be aware that changing the size of input data may change the ranking of speed and memory. The speed of a library may vary up to 10% in two different runs.</li>
<li>CPU time is measured in seconds. Memory denotes the peak memory, measured in MB.</li>
<li>For string hash, only the pointer to a string is inserted. Memory in the table does not count the space used by strings.</li>
<li>If two numbers are given for memory, the first is for integer keys and the second for string keys.</li>
<li>For all C++ libraries and khash.h, one operation is needed to achieve &#8220;insert if absent; delete otherwise&#8221;. Glib and ghthash require two operations, which does not favour these two libraries.</li>
<li>The speed may also be influenced by the efficiency of hash funtions. Khash and Glib use the same hash function. TR1/SGI-STL/google-hash use another hash function. Fortunately, to my experiment, the two string hash functions have quite similar performance and so the benchmark reflects the performance of the overall hash libraries instead of just hash functions.</li>
<li>For glib and ghthash, what is inserted is the pointer to the integer instead of the integer itself.</li>
<li>Ghthash supports dynamic hash table. However, the results do not seem correct when this is switched on. I am using fixed-size hash table. This favours ghthash.</li>
<li>CC&#8217;s hashtable will force to free a key, which is not implemented in all the other libraries. This behaviour will add overhead on both speed and memory in my benchmark (but probably not in other applications). The memory is measured for integer keys.</li>
<li>This simple benchmark does not test the strength and weakness of splay tree.</li>
</ul>
<p>And here is the result of the second experiment:</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td>Library</td>
<td>grow</td>
<td>pred/grow</td>
<td>replace</td>
<td>fetch</td>
<td>fetchnull</td>
<td>remove</td>
<td>Memory</td>
</tr>
<tr>
<td>TR1</td>
<td>194.2</td>
<td>183.9</td>
<td>30.7</td>
<td>15.6</td>
<td>15.2</td>
<td>83.4</td>
<td>224.6</td>
</tr>
<tr>
<td>STL hash_map</td>
<td>149.0</td>
<td>110.5</td>
<td>35.6</td>
<td>11.5</td>
<td>14.0</td>
<td>87.2</td>
<td>204.2</td>
</tr>
<tr>
<td>STL map</td>
<td>289.9</td>
<td>289.9</td>
<td>141.3</td>
<td>134.3</td>
<td>7.0</td>
<td>288.6</td>
<td>236.8</td>
</tr>
<tr>
<td>google-sparse</td>
<td>417.2</td>
<td>237.6</td>
<td>89.5</td>
<td>84.0</td>
<td>12.1</td>
<td>100.4</td>
<td>85.4</td>
</tr>
<tr>
<td>google-dense</td>
<td>108.4</td>
<td>39.4</td>
<td>17.8</td>
<td>8.3</td>
<td>2.8</td>
<td>18.0</td>
<td>256.0</td>
</tr>
<tr>
<td>khash (C++)</td>
<td>111.2</td>
<td>99.2</td>
<td>26.1</td>
<td>11.5</td>
<td>3.0</td>
<td>17.4</td>
<td>198.0</td>
</tr>
</tbody>
</table>
<p>Notes:</p>
<ul>
<li>CPU time is measured in nanosecond for each operation. Memory is measured by TCmalloc. It is the memory difference before and after the allocation of the hash table, instead of the peak memory.</li>
<li>In this experiment, integers are inserted in order and there are no collisions in the hash table.</li>
<li>All these libraries provide similar API.</li>
</ul>
<p><strong>Discussions</strong></p>
<ul>
<li><strong>Speed and memory.</strong> The larger the hash table, the fewer collisions may occur and the faster the speed. For the same hash library, increasing memory always increases speed. When we compare two libraries, both speed and memory should be considered.</li>
<li><strong>C vs. C++.</strong> All C++ implementations have similar API. It is also very easy to use for any type of keys. Both C libraries, ghthash and glib, can only keep pointers to the keys, which complicates API and increases memory especially for 64-bit systems where a pointer takes 8 bytes. In general, C++ libraries is perferred over C ones. Surprisingly, on 32-bit Mac OS X, glib outperforms TR1 and STL for string input. This might indicate that the glib implementation itself is very efficient, but just the lack of functionality in C affects the performance.</li>
<li><strong>Generic programming in C</strong>. Except my khash.h, all the other C hash libraries use (void*) to achieve generic typing. Using void* is okey for strings, but will cause overhead for integers. This is why all C libraries, except khash.h, is slower than C++ libraries on integer keys, but close to on string keys.</li>
<li><strong>Open addressing vs. chaining hash.</strong> Khash and google hash implement open addressing hash while the remaining implement chaining hash. In open addressing hash, the size of each bucket equals the size of a key plus 0.25 byte. Google sparsehash further compresses unused bucket to 1 bit, achieving high memory efficiency. In chaining hash, the memory overhead of each bucket is at least 4 bytes on 32bit machines, or 8 bytes on 64bit machines. However, chaining hash is less affected when the hash table is nearly full. In practice, both open addressing and chaining hash occupy similar memory under similar speed. Khash takes less peak memory mainly due to its advanced technique in rehashing which reduces memory usage. So far as speed is concerned, chaining hash may have fewer comparison between keys. We can see this from the fact that the speed of chaining hash approaches that of open addressing hash on string keys but much slower on integer keys.</li>
<li><strong>Memory usage of search trees. </strong>B-tree is the winner here. Each element in the B-tree only needs one additional pointer. When there are enough elements, a B-tree is at least halfly full; on average it should be around 75% full. And so on 64-bit systems, for a B-tree with N elements, we need additional N*8/0.75=10N bytes memory. Splay tree will need N*8*2=16N extra space. RB tree is the worst.</li>
<li><strong>Other issues.</strong> a) Google hash becomes unbearably slow when I try to put a lot of strings in the hash table. All the other libraries do not have this problem. b) Google hash performs more comparisons than khash. This is obvious because google-dense is clearly faster on integer keys but comparable to khash on string keys.</li>
</ul>
<p><strong>Concluding remarks</strong></p>
<ul>
<li>C++ hash library is much easier to use than C libraries. This is definitely where C++ is preferred over C.</li>
<li>TR1 hash implementation is no faster than STL implementation. They may outperform one another under certain input or settings.</li>
<li>SGI hash_map is faster and takes less memory than STL map. Unless ordering is important, hash_map is a better container than map.</li>
<li>Google hash is a worthy choice when we understand why it is slow for many string keys.</li>
<li>My khash library, which is a single-file C++ template header, achieves good balance between speed and memory. All my source codes are available at the <a href="http://attractivechaos.wordpress.com/programs/">Programs page</a>.</li>
</ul>
<p><strong>Update</strong></p>
<ol>
<li>C interface can be elegant, too, if we implement it cleverly. See <a href="http://attractivechaos.wordpress.com/2008/09/02/implementing-generic-hash-library-in-c/">this post</a>.</li>
<li>I realize that we just need one lookup to achieve &#8220;insert if absent; delete otherwise&#8221;. This further improves the speed for all C++ libraries.</li>
<li>I have analyzed google dense hash table in <a href="http://attractivechaos.wordpress.com/2008/09/12/the-google-hash-table-library/">this post</a> which explains why it is faster than khash on integer keys but close to or slower than on string keys.</li>
<li><a href="http://compilers.iecc.com/comparch/article/07-04-089">This thread</a> directed me to <a href="http://gcc.gnu.org/viewcvs/trunk/libiberty/hashtab.c?view=log">gcc hashtable</a>, and <a href="http://cocom.cvs.sourceforge.net/cocom/cocom/AMMUNITION/">cocom hashtable</a>. They are more or less independent of other source codes, but it would still take time to separate the source codes. So, I have not benchmarked them. Just keep a record.</li>
<li> <a href="http://svn.python.org/view/python/trunk/Objects/">Python dictionary</a> is in fact a hash table. The <a href="http://svn.python.org/view/python/trunk/Objects/dictnotes.txt?rev=53782&amp;view=markup">dictnotes.txt</a> in that directory gives some quite interesting discussion about how to implement hash efficiently.</li>
<li><a href="http://cbfalconer.home.att.net/download/">hashlib</a> library. A bit hard to use and I cannot get it running correctly. Possibly I have not provided a proper second hash function for rehashing.</li>
<li>Added results for STL set (based on red-black tree) and John-Mark Gurney&#8217;s <a href="http://resnet.uoregon.edu/~gurney_j/jmpc/btree.html">B-tree implementation</a> (JG&#8217;s btree). Both libraries are considerably slower than hash tables. Of course search trees provide more functionality than hash tables, and every nice thing comes with a price. I have also tried Jason Evans&#8217;s and Niels Provos&#8217; red-black tree implementations. On integer keys, JE&#8217;s takes 6.110 seconds on Mac-Intel using 18.884 MB memory and NP&#8217;s taks 6.611 seconds using the same amount of memory. This performance is close to that of STL set. They appear to be slower mainly due to the additional malloc/free calls I have to made under their APIs. Unlike hash table which have a variety of ways to implement it, red-black tree usually has one way (well, can be more. See also Jason&#8217;s blog.). And so I only show the performance of STL set as a representitive.</li>
<li>Replaced JG&#8217;s B-tree with a modified version. The new version is both faster and more light-weighted.</li>
</ol>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/attractivechaos.wordpress.com/278/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/attractivechaos.wordpress.com/278/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/attractivechaos.wordpress.com/278/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/attractivechaos.wordpress.com/278/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/attractivechaos.wordpress.com/278/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/attractivechaos.wordpress.com/278/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/attractivechaos.wordpress.com/278/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/attractivechaos.wordpress.com/278/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/attractivechaos.wordpress.com/278/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/attractivechaos.wordpress.com/278/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/attractivechaos.wordpress.com/278/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/attractivechaos.wordpress.com/278/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=attractivechaos.wordpress.com&blog=4545823&post=278&subd=attractivechaos&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://attractivechaos.wordpress.com/2008/08/28/comparison-of-hash-table-libraries/feed/</wfw:commentRss>
		<slash:comments>27</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/047ebc7bb9ff37a0da844413856e92cb?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">attractivechaos</media:title>
		</media:content>
	</item>
		<item>
		<title>Comparison of Internal Sorting Algorithms</title>
		<link>http://attractivechaos.wordpress.com/2008/08/28/comparison-of-internal-sorting-algorithms/</link>
		<comments>http://attractivechaos.wordpress.com/2008/08/28/comparison-of-internal-sorting-algorithms/#comments</comments>
		<pubDate>Thu, 28 Aug 2008 08:29:20 +0000</pubDate>
		<dc:creator>attractivechaos</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[benchmark]]></category>
		<category><![CDATA[cpp]]></category>
		<category><![CDATA[myprog]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://attractivechaos.wordpress.com/?p=240</guid>
		<description><![CDATA[Sorting algorithm
Given an array of size N, sorting can be done in O(N log(N)) in average. The most frequently used sorting algorithms that can achieve this time complexity are quicksort, heapsort and mergesort. They usually require O(log(N)), O(1) and O(N) working space, respectively (the space complexity of mergesort can be improved at the cost of [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=attractivechaos.wordpress.com&blog=4545823&post=240&subd=attractivechaos&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><strong>Sorting algorithm</strong></p>
<p><strong></strong>Given an array of size N, sorting can be done in O(N log(N)) in average. The most frequently used sorting algorithms that can achieve this time complexity are quicksort, heapsort and mergesort. They usually require O(log(N)), O(1) and O(N) working space, respectively (the space complexity of mergesort can be improved at the cost of speed). Most people believe quicksort is the fastest sorting algorithm. However, the fact is quicksort is only fast in terms of the number of swaps. When comparison is expensive, mergesort is faster than quicksort because mergesort uses less comparisons. GNU sort uses mergesort. Replacing it with a quicksort reduces the speed on typical text input. In addition, of the three algorithms, only mergesort is a stable sort. Stability is sometimes useful for a general tool like GNU sort.</p>
<p>The worst-case time complexity of quicksort is O(N^2). In practice, we combine quicksort and heapsort to avoid worst-case performance while retaining the fast average speed. The resulting algorithm is called introsort (introspective sort).</p>
<p><strong>Implementation</strong></p>
<p>The two most widely used implementations are glibc qsort and STL (unstable) introsort. Libc qsort calls a function for comparison. For simple comparison, a function call is expensive, which may greatly hurt the efficiency of qsort. STL sort does not have this problem. It is one of the fastest implementations I am aware of. My own implementation of introsort is similar but not as fast as STL introsort.</p>
<p>GNU sort implements a top-down recursive sort. On integer sorting, it is twice slower than introsort (see below). Iterative top-down mergesort is hard to implement. Iterative bottom-up mergesort is much easier. My implementation is a bottom-up one.</p>
<p>Paul Hsieh has also implemented quicksort, heapsort and mergesort. His implementation should be very efficient from what I can tell. To see whether my implementation is good enough, I copied and pasted his codes in my program, and applied &#8220;inline&#8221; where necessary.</p>
<p><strong>Comparison</strong></p>
<p>I designed a small benchmark on sorting 50 million random integers. As comparison is cheap in this case, the number of swaps dominate the performance. I compiled and run the program on three machines: MacIntel (Core2-2G/Mac/g++-4.2.1), LinuxIntel (Xeon-1.86G/Linux/g++-4.1.2) and LinuxAMD (Opteron-2G/Linux/g++-3.4.4). On all the three platforms, the program was compiled with &#8220;-O2 -fomit-frame-pointer&#8221;. The time (in seconds) spent on sorting is showed in the following table:</p>
<table border="1" cellspacing="0">
<tbody>
<tr>
<td style="text-align:left;">Algorithm</td>
<td>MacIntel</td>
<td>LinuxIntel</td>
<td>LinuxAMD</td>
<td>Linux_icc</td>
</tr>
<tr>
<td>STL sort</td>
<td>7.749</td>
<td>8.260</td>
<td>7.170</td>
<td>8.400</td>
</tr>
<tr>
<td>STL stable_sort</td>
<td>9.684</td>
<td>11.990</td>
<td>10.270</td>
<td>10.770</td>
</tr>
<tr>
<td>libc qsort</td>
<td>16.579</td>
<td>81.190</td>
<td>30.490</td>
<td>81.120</td>
</tr>
<tr>
<td>introsort</td>
<td>7.887</td>
<td>8.880</td>
<td>7.670</td>
<td>9.320</td>
</tr>
<tr>
<td>iterative mergesort</td>
<td>10.371</td>
<td>12.480</td>
<td>10.110</td>
<td>10.130</td>
</tr>
<tr>
<td>binary heapsort</td>
<td>36.651</td>
<td>45.710</td>
<td>42.460</td>
<td>40.820</td>
</tr>
<tr>
<td>combsort11</td>
<td>18.131</td>
<td>19.290</td>
<td>19.370</td>
<td>19.490</td>
</tr>
<tr>
<td>isort (func call)</td>
<td>16.760</td>
<td>17.380</td>
<td>13.390</td>
<td>16.740</td>
</tr>
<tr>
<td>isort (template func)</td>
<td>7.902</td>
<td>8.800</td>
<td>7.690</td>
<td>9.010</td>
</tr>
<tr>
<td>Paul&#8217;s heapsort</td>
<td>34.790</td>
<td>43.680</td>
<td>40.740</td>
<td>39.060</td>
</tr>
<tr>
<td>Paul&#8217;s quicksort</td>
<td>8.410</td>
<td>8.940</td>
<td>7.810</td>
<td>9.450</td>
</tr>
<tr>
<td>Paul&#8217;s mergesort</td>
<td>11.103</td>
<td>13.390</td>
<td>10.680</td>
<td>13.030</td>
</tr>
</tbody>
</table>
<p>As for the algorithm itself, we can see that introsort is the fastest and heapsort is the slowest. Mergesort is also very fast. Combsort11 is claimed to approach quicksort, but I do not see this in sorting large integer arrays. As for the implementation of quicksort/introsort, STL is the best, with my implementation following very closely. Paul&#8217;s implmentation is also very efficient. Libc qsort is clearly slower, which cannot simply attribute to the use of function calls. My implementation with function calls, although slower than without function calls, outperforms libc qsort on both Linux machines. As for the implementation of mergesort, my version has similar performance to STL stable_sort. Note that stable_sort uses buffered recursive mergesort when a temporary array can be allocated. When memory is insufficient, it will use in-place mergesort which is not evaluated here.</p>
<p><strong>Availability and alternative benchmarks</strong></p>
<p>My implementation is available <a href="http://www.freewebs.com/attractivechaos/sort.hh.html">here</a> as a single C++ template header file. The program for benchmark is also <a href="http://www.freewebs.com/attractivechaos/sort_test.cc.html">available</a>. Programs in plain text can be acquired by chopping .html in the two links.</p>
<p>Paul Hsieh&#8217;s benchmark is <a href="http://www.softpanorama.org/Algorithms/sorting.shtml">here</a>, including the original <a href="http://www.azillionmonkeys.com/qed/sorttest.c">source codes</a>. He also discussed how algorithms perform when the initial array is not completely random (I am one of &#8220;naive people&#8221; in his standard). Please note that in his benchmark, he was sorting an array of size 60,000 for 10000 times, while in my benchmark I more focus on very large arrays. Notably, heapsort approaches introsort on small arrays, but far slower on large arrays. Presumably this is because the bad cache performance of heapsort. Both quicksort and mergesort are very cache efficient.</p>
<p>In addition to Paul&#8217;s benchmark, you can also find alternative ones <a href="http://www.cs.rpi.edu/%7Emusser/gp/code/read1.dat.txt">here</a> and <a href="http://ralphunden.net/content/tutorials/a-guide-to-introsort/">here</a>. They seem to be more interested in the theoretical issues rather than efficient practical implementations.</p>
<p>If you search &#8220;benchmark sorting algorithms&#8221; in google, the first result is <a href="http://www.digitalmars.com/d/archives/digitalmars/D/announce/Sorting_algorithms_benchmark_7661.html">this page</a>, which was implemented in D by Stewart Gordon. This benchmark aims to evaluate the performance on small arrays. It also tests the speed when the array is sorted or reverse sorted. However, the implementation is not optimized enough at least for quicksort. Using insertion sort when the array is nearly sorted is always preferred. You can also find <a href="http://www.arcle.com/readings/sorting_algorithm_benchmark.pdf">this report</a> from google search, but the implementation of quicksort is too naive to be efficient.</p>
<p><strong>Concluding remarks</strong></p>
<p><strong></strong>Although in the table introsort performs the best, we may want to use mergesort if we want to perform stable sorting, or the comparison is very expensive. Mergesort is also faster than introsort if the array is nearly sorted. STL sort seems to take particular care in this case, which makes it still fast when the array is sorted.</p>
<p>In common cases when comparison is cheap, introsort is the best choice. Of the various implementations, STL is the fastest. If you do not use STL or you just want to use C, you can use/adapt my implmentation which is very close to STL sort in speed. Do not use libc qsort, especially on Linux. It is not well implemented.</p>
<p>Update</p>
<ol>
<li><a href="http://warp.povusers.org/">This website</a> gives severl <a href="http://warp.povusers.org/SortComparison/">good implementations</a> of sorting algorithms. I also believe the programmer behind is very capable. Highly recommended.</li>
</ol>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/attractivechaos.wordpress.com/240/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/attractivechaos.wordpress.com/240/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/attractivechaos.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/attractivechaos.wordpress.com/240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/attractivechaos.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/attractivechaos.wordpress.com/240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/attractivechaos.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/attractivechaos.wordpress.com/240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/attractivechaos.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/attractivechaos.wordpress.com/240/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/attractivechaos.wordpress.com/240/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/attractivechaos.wordpress.com/240/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=attractivechaos.wordpress.com&blog=4545823&post=240&subd=attractivechaos&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://attractivechaos.wordpress.com/2008/08/28/comparison-of-internal-sorting-algorithms/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/047ebc7bb9ff37a0da844413856e92cb?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">attractivechaos</media:title>
		</media:content>
	</item>
		<item>
		<title>The Best Multialignment Program?</title>
		<link>http://attractivechaos.wordpress.com/2008/08/21/the-best-multialignment-program/</link>
		<comments>http://attractivechaos.wordpress.com/2008/08/21/the-best-multialignment-program/#comments</comments>
		<pubDate>Thu, 21 Aug 2008 09:17:39 +0000</pubDate>
		<dc:creator>attractivechaos</dc:creator>
				<category><![CDATA[research]]></category>
		<category><![CDATA[alignment]]></category>
		<category><![CDATA[benchmark]]></category>
		<category><![CDATA[multialignment]]></category>

		<guid isPermaLink="false">http://attractivechaos.wordpress.com/?p=128</guid>
		<description><![CDATA[Popular multialignment programs include: clustalw, T-coffee, dialign [PMID: 18505568, 10222408], muscle [PMID: 15318951], MAFFT [PMID: 18372315], probcons [PMID: 15687296] and probalign [PMID: 16954142]. Which is the best in practice? You can find various benchmarks in the papers listed above. I only summarize based on my understanding. It is recommended to read their papers in case [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=attractivechaos.wordpress.com&blog=4545823&post=128&subd=attractivechaos&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Popular multialignment programs include: clustalw, T-coffee, dialign [PMID: <a href="http://www.ncbi.nlm.nih.gov/pubmed/18505568">18505568</a>, <a href="http://www.ncbi.nlm.nih.gov/pubmed/10222408">10222408</a>], muscle [PMID: <a href="http://www.ncbi.nlm.nih.gov/pubmed/15318951">15318951</a>], MAFFT [PMID: <a href="http://www.ncbi.nlm.nih.gov/pubmed/18372315">18372315</a>], probcons [PMID: <a href="http://www.ncbi.nlm.nih.gov/pubmed/15687296">15687296</a>] and probalign [PMID: <a href="http://www.ncbi.nlm.nih.gov/pubmed/16954142">16954142</a>]. Which is the best in practice? You can find various benchmarks in the papers listed above. I only summarize based on my understanding. It is recommended to read their papers in case my summary is biased. Also, both accuracy and speed may vary a lot with different data sets. I can only give results based on the data used in their papers.</p>
<p>Firstly, these software can be divided into two groups: those performing global multiple alignment and those performing local multiple alignment. In global alignment, each residue of each sequence is required to be aligned. This category includes clustalw, T-coffee, muscle, probcons and probalign. In local alignment, some residues are allowed to be unaligned. Only segments that closely related are aligned together. This category includes dialign family and MAFFT. They can also perform global alignment.</p>
<p>Most benchmarks are designed for global aligners. The consensus seems to be:</p>
<ul>
<li>accuracy: probalign&gt;probcons&gt;MAFFT&gt;muscle&gt;T-coffee&gt;&gt;clustalw~dialign</li>
<li>speed:  clustalw~muscle&gt;MAFFT&gt;dialign&gt;&gt;probcons&gt;probalign~T-coffee</li>
</ul>
<p>Only MAFFT and dialign performs local alignment. The dialign paper claims that dialign is much more accurate. However, I doubt this largely depends on the definition of high-scoring segments. We can always find tighter alignment by excluding more residues.</p>
<p>Then, what is the best? Muscle or MAFFT. Although probcons and probalign are more accurate, they run impractically slower than muscle and MAFFT. As for the winner between muscle and MAFFT, I cannot decide. I also need to evaluate the memory consumption, usability and stability. I have only used muscle. It is really nice software!</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/attractivechaos.wordpress.com/128/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/attractivechaos.wordpress.com/128/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/attractivechaos.wordpress.com/128/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/attractivechaos.wordpress.com/128/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/attractivechaos.wordpress.com/128/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/attractivechaos.wordpress.com/128/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/attractivechaos.wordpress.com/128/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/attractivechaos.wordpress.com/128/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/attractivechaos.wordpress.com/128/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/attractivechaos.wordpress.com/128/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/attractivechaos.wordpress.com/128/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/attractivechaos.wordpress.com/128/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=attractivechaos.wordpress.com&blog=4545823&post=128&subd=attractivechaos&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://attractivechaos.wordpress.com/2008/08/21/the-best-multialignment-program/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/047ebc7bb9ff37a0da844413856e92cb?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">attractivechaos</media:title>
		</media:content>
	</item>
		<item>
		<title>Biased Benchmarks on Short Read Aligners: ZOOM</title>
		<link>http://attractivechaos.wordpress.com/2008/08/19/biased-benchmarks-on-short-read-aligners-zoom/</link>
		<comments>http://attractivechaos.wordpress.com/2008/08/19/biased-benchmarks-on-short-read-aligners-zoom/#comments</comments>
		<pubDate>Tue, 19 Aug 2008 11:27:50 +0000</pubDate>
		<dc:creator>attractivechaos</dc:creator>
				<category><![CDATA[research]]></category>
		<category><![CDATA[alignment]]></category>
		<category><![CDATA[benchmark]]></category>
		<category><![CDATA[NGS]]></category>
		<category><![CDATA[opinion]]></category>

		<guid isPermaLink="false">http://attractivechaos.wordpress.com/?p=32</guid>
		<description><![CDATA[ZOOM [PMID:18684737] is still unavailable even when the manuscript goes online. For the time being, there is no way to confirm whether their benchmarks are unbiased. Fortunately, we can collect some information from what they have presented. In the ZOOM paper, the authors give the memory consumption of ZOOM. It is 2.9GB for 12 million [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=attractivechaos.wordpress.com&blog=4545823&post=32&subd=attractivechaos&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><a href="http://www.bioinformaticssolutions.com/products/zoom/index.php">ZOOM</a> [PMID:<a href="http://www.ncbi.nlm.nih.gov/pubmed/18684737">18684737</a>] is still unavailable even when the manuscript goes online. For the time being, there is no way to confirm whether their benchmarks are unbiased. Fortunately, we can collect some information from what they have presented. In the ZOOM paper, the authors give the memory consumption of ZOOM. It is 2.9GB for 12 million short reads. So far as I know, Eland will only use 30~40% of this memory. If Anthony Cox had meant to use more memory, he would have achieved faster speed. In addition, apparently ZOOM only reports the unique best hit according to <a href="http://seqanswers.com/forums/showthread.php?t=43&amp;page=4">this post</a>. Eland will count the occurrences of all the 0-, 1- and 2-mismatch hits anyway. In fact, if you read eland source codes, you will know that counting occurrences is non-trivial and it is much more expensive to implement counting in ZOOM than in Eland. I bet ZOOM would be slower than Eland if it generates the same output as Eland. Of course, it is not always necessary to generate the same output, but detecting unique best hits alone are usually not good enough in some applications, such as detecting structural variations. We need to know whether there are many suboptimal hits with scores close to the best one.</p>
<p>Although the benchmark is biased, the ZOOM paper itself indeed presents an elegant idea about using non-contiguous seeds. I also believe ZOOM is highly tuned for performance by a group of strong programmers. Furthermore, even if ZOOM is slower than Eland, I would still prefer ZOOM as it eliminates the hard limits on the 32bp read length and the maximum two mismatches. I do not mind if ZOOM is a bit slower. I just want to see a fair comparison.</p>
<p>Update: ZOOM has been released and I have tried it a bit. The claim in the paper is honest: ZOOM is indeed faster than Eland while allowing longer reads. Nonetheless, ZOOM only reports unique best hits and therefore my claim here is fair, too: Eland is giving more information, which is one of the reasons that it is slower. Although ZOOM can output N top hits, apparently we can only achieve this by dumping all the potential hits. On human alignment, this is impractical.</p>
<p>Note that I pay a lot of attention to ZOOM mainly because it is a great software. In terms of efficiency and usability, ZOOM is much better than many other similar software that I have not mentioned here.</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/attractivechaos.wordpress.com/32/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/attractivechaos.wordpress.com/32/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/attractivechaos.wordpress.com/32/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/attractivechaos.wordpress.com/32/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/attractivechaos.wordpress.com/32/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/attractivechaos.wordpress.com/32/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/attractivechaos.wordpress.com/32/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/attractivechaos.wordpress.com/32/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/attractivechaos.wordpress.com/32/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/attractivechaos.wordpress.com/32/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/attractivechaos.wordpress.com/32/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/attractivechaos.wordpress.com/32/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=attractivechaos.wordpress.com&blog=4545823&post=32&subd=attractivechaos&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://attractivechaos.wordpress.com/2008/08/19/biased-benchmarks-on-short-read-aligners-zoom/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/047ebc7bb9ff37a0da844413856e92cb?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">attractivechaos</media:title>
		</media:content>
	</item>
	</channel>
</rss>