Note that there are some explanatory texts on larger screens.

plurals
  1. POEfficient integer compare function
    primarykey
    data
    text
    <p>The <code>compare</code> function is a function that takes two arguments <code>a</code> and <code>b</code> and returns an integer describing their order. If <code>a</code> is smaller than <code>b</code>, the result is some negative integer. If <code>a</code> is bigger than <code>b</code>, the result is some positive integer. Otherwise, <code>a</code> and <code>b</code> are equal, and the result is zero.</p> <p>This function is often used to parametrize sorting and searching algorithms from standard libraries.</p> <p>Implementing the <code>compare</code> function for characters is quite easy; you simply subtract the arguments:</p> <pre><code>int compare_char(char a, char b) { return a - b; } </code></pre> <p>This works because the difference between two characters is generally assumed to fit into an integer. (Note that this assumption does not hold for systems where <code>sizeof(char) == sizeof(int)</code>.)</p> <p>This trick cannot work to compare integers, because the difference between two integers generally does not fit into an integer. For example, <code>INT_MAX - (-1) = INT_MIN</code> suggests that <code>INT_MAX</code> is smaller than <code>-1</code> (technically, the overflow leads to undefined behavior, but let's assume modulo arithmetic).</p> <p>So how can we implement the compare function efficiently for integers? Here is my first attempt:</p> <pre><code>int compare_int(int a, int b) { int temp; int result; __asm__ __volatile__ ( "cmp %3, %2 \n\t" "mov $0, %1 \n\t" "mov $1, %0 \n\t" "cmovg %0, %1 \n\t" "mov $-1, %0 \n\t" "cmovl %0, %1 \n\t" : "=r"(temp), "=r"(result) : "r"(a), "r"(b) : "cc"); return result; } </code></pre> <p>Can it be done in less than 6 instructions? Is there a less straightforward way that is more efficient?</p>
    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.
 

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