Re: branch prediction optimization
- From: moi <root@xxxxxxxxxxxxxxxxxxxxx>
- Date: Sat, 24 Mar 2007 13:29:25 +0100
On Thu, 22 Mar 2007 22:12:51 -0700, Frank Cusack wrote:
Hi
I guess some processors have special branch instructions where you can
inform the CPU which path is likely to be taken. I assume this must
be a useful optimization otherwise why have the special instructions.
If you had a loop like
head = NULL;
tail = NULL;
while (more_data) {
n = new_node();
munge data;
if (tail)
tail->next = n;
else
head = n;
tail = n;
}
and wanted to avoid the branch misprediction penalty, you could
"manually" create the head node first, then enter a loop to append all
following nodes.
Is there a way to tell the compiler (say gcc) that the 'if (tail)' will
be false the first time through the loop and true the rest of the time?
Just curious. I can't really think of an application for this. If it
really mattered you could use likely() and unlikely() like in the
linux kernel, although the first time through the loop will suffer.
I guess some processors will automatically predict the same path as
the last time, thus auto-optimizing this for you. Is that right, or
did I just make that up.
-frank
Just a thought:
#include <stdlib.h>
struct node {
struct node *next;
};
main()
{
int more_data;
struct node *head, **tail;
head = NULL;
tail = &head;
while(more_data ^= random()) {
*tail = malloc(sizeof **tail);
tail = &(*tail)->next;
}
}
Would contain only one condition (more_data), which could be massaged into
the right branch-prediction behaviour. GCC -S- -O8 compiles the main loop
into:
leal -16(%ebp), %esi
jmp .L2
.p2align 4,,7
..L3:
movl $4, (%esp)
call malloc
movl %eax, (%esi)
movl %eax, %esi
..L2:
call random
xorl %eax, %ebx
jne .L3
Which is (given the unpredictability of the loop condition)
about perfect, IMHO.
HTH,
AvK
.
- Follow-Ups:
- Re: branch prediction optimization
- From: Rainer Weikusat
- Re: branch prediction optimization
- From: Frank Cusack
- Re: branch prediction optimization
- References:
- branch prediction optimization
- From: Frank Cusack
- branch prediction optimization
- Prev by Date: Re: Program that wakes up every hour
- Next by Date: Re: Remove File Descriptor from poll() set
- Previous by thread: Re: branch prediction optimization
- Next by thread: Re: branch prediction optimization
- Index(es):
Relevant Pages
|
|