Note that there are some explanatory texts on larger screens.

plurals
  1. POOptimisation for a brainfuck interpreter
    primarykey
    data
    text
    <p>As an exercise to help me learn about interpreters and optimisation, neither of which I know anything about, I have written a brainfuck interpreter in C. It appears to work flawlessly thus far, though it does not compete well in execution speed compared to other fast interpreters.</p> <p>What are some ways that I can change this interpreter to improve performance (or otherwise)?</p> <p>One interesting aspect of my interpreter (though most others probably do this as well) is that I run one loop that reads through the source input and converts each instruction into a</p> <pre><code>struct { long instruction; long loop; } </code></pre> <p>The <code>loop</code> value is the index of the matching <code>]</code> instruction, if the instruction is a <code>[</code>, and the index of the matching <code>[</code> instruction, if the instruction is a <code>]</code>, allowing quick jumping. I'd imagine that this 'parsing' process (which doesn't take long) improves execution times over doing redundant reparsing to find matching square brackets every time they are needed.</p> <p>An interesting test of brainfuck interpreter speed is this program:</p> <pre><code>++++++++[-&gt;-[-&gt;-[-&gt;-[-]&lt;]&lt;]&lt;]&gt;++++++++[&lt;++++++++++&gt;-]&lt;[&gt;+&gt;+&lt;&lt;-]&gt;-.&gt;-----.&gt; </code></pre> <ol> <li><a href="http://azabani.com/cgit.cgi/brief/plain/brief.c?id=0884ccb22287158fd3664eb83427444644aaa328" rel="nofollow noreferrer">the first version of the interpreter</a></li> <li><a href="http://azabani.com/cgit.cgi/brief/plain/brief.c?id=92a1dc40c549e25927831fee469429a9ab3be293" rel="nofollow noreferrer">the interpreter</a> after implementing <a href="https://stackoverflow.com/questions/6853548/optimisation-for-a-brainfuck-interpreter/6853750#6853750">Jerry Coffin's answer</a>, which removes the giant switch in the runtime loop, by making the <code>instruction</code> struct's <code>instruction</code> a direct pointer to an operation function - <em>this runs slower than the previous version (function call overhead?)</em></li> <li><a href="http://azabani.com/cgit.cgi/brief/plain/brief.c?id=c7fd6e04a88a60bd9ec480c00718ca7d91834898" rel="nofollow noreferrer">the interpreter</a> after <strong>reversing the previous change</strong> and adding an optimisation to 'collapse' multiple consecutive non-loop operations, reducing loop cycles - <em>this runs slightly faster than the original</em></li> </ol>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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