Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Measuring things, part 2. I have now got two programs. The first is in C and is compiled with gcc -O2:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;time.h&gt; #define BIG 1000000 int f( int n ) { int r = 0, i = 0; for ( i = 0; i &lt; 1000; i++ ) { r += i; if ( n == BIG - 1 ) { return -1; } } return r; } int main() { clock_t start = clock(); int i = 0, z = 0; for ( i = 0; i &lt; BIG; i++ ) { if ( (z = f(i)) == -1 ) { break; } } double t = (double)(clock() - start) / CLOCKS_PER_SEC; printf( "%f\n", t ); printf( "%d\n", z ); } </code></pre> <p>The second is C++, with exception handling, compiled with g++ -O2:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;time.h&gt; #define BIG 1000000 int f( int n ) { int r = 0, i = 0; for ( i = 0; i &lt; 1000; i++ ) { r += i; if ( n == BIG - 1 ) { throw -1; } } return r; } int main() { clock_t start = clock(); int i = 0, z = 0; for ( i = 0; i &lt; BIG; i++ ) { try { z += f(i); } catch( ... ) { break; } } double t = (double)(clock() - start) / CLOCKS_PER_SEC; printf( "%f\n", t ); printf( "%d\n", z ); } </code></pre> <p>I think these answer all the criticisms made of my last post.</p> <p><strong>Result: Execution times give the C version a 0.5% edge over the C++ version with exceptions, not the 10% that others have talked about (but not demonstrated)</strong></p> <p><strong><em>I'd be very grateful if others could try compiling and running the code (should only take a few minutes) in order to check that I have not made a horrible and obvious mistake anywhere. This is knownas "the scientific method"!</em></strong></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload