473,769 Members | 6,404 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

low-level, ugly pointer arithmetics


Hi!

I'm trying to squeeze a few clock cycles from a tight
loop that profiling shows to be a bottleneck in my program.
I'm at a point where the only thing that matters is
execution speed, not style (within the loop, obviously).

The loop deals with an array:

// this is aligned at cache line boundaries
struct hash_t {
int id;
int next;
double d0;
double d1;
double d2;
} hashtable[HASH_MAX];

within the loop, whenever there is a hashtable miss I
need to store new values into hashtable[index].
Originally this looked like

if(...) {
hashtable[index].id=some_int;
hashtable[index].next=some_int2 ;
hashtable[index].d0=some_double 0;
hashtable[index].d1=some_double 1;
hashtable[index].d2=some_double 2;
}

Now... I'm trying to save a few cycles by doing something
along the lines of

if(...) {
// point to the first member
int *hashtable_ptr = reinterpret_cas t<int*&(hashtab le[index].id)
*(hashtable_ptr ++) = some_int; // store into id and move on
*(hashtable_ptr ++) = some_int2; // store into next and move on
*(hashtable_ptr ++) = some_double0; // << --- trouble
// ...
}

the trouble is that I'm working with a pointer to int
and I want to store a double and, later on, advance the
pointer not by sizeof(int) bytes, but by sizeof(double)
bytes. On my system sizeof(int) is 4, sizeof(double) is 8
and portability is not an issue.

I tried

*((reinterpret_ cast<double*>(h ashtable_ptr))+ +) = some_double0;

but I got an error:

"the result of this cast cannot be used as an lvalue".

Why's that? I really need to force the compiler to treat
this pointer as a double* for a moment... I realize I can
have two pointers to the same hashtable entry, one an int*
and one a double*, but I need to save every clock cycle I
can as this loop is executed trillions of times.

What's the usual procedure to iterate a pointer through
members of varying types? Perhaps it would be easier with
a char*, but that means advancing by 4 and 8 which,
I suppose, would be slower than plain ++? Or does it boil
to moving by 4 or 8 offsets at the assembly level too?

thanks in advance,
- J.

PS. Are pointers to different datatypes guaranteed to
be of the same size? If not, than perhaps I need
an assert here and there...
Sep 7 '06 #1
18 2245
Jacek Dziedzic wrote:
Hi!

I'm trying to squeeze a few clock cycles from a tight
loop that profiling shows to be a bottleneck in my program.
I'm at a point where the only thing that matters is
execution speed, not style (within the loop, obviously).

The loop deals with an array:

// this is aligned at cache line boundaries
struct hash_t {
int id;
int next;
double d0;
double d1;
double d2;
} hashtable[HASH_MAX];

within the loop, whenever there is a hashtable miss I
need to store new values into hashtable[index].
Originally this looked like

if(...) {
hashtable[index].id=some_int;
hashtable[index].next=some_int2 ;
hashtable[index].d0=some_double 0;
hashtable[index].d1=some_double 1;
hashtable[index].d2=some_double 2;
}

Now... I'm trying to save a few cycles by doing something
along the lines of

if(...) {
// point to the first member
int *hashtable_ptr = reinterpret_cas t<int*&(hashtab le[index].id)
*(hashtable_ptr ++) = some_int; // store into id and move on
*(hashtable_ptr ++) = some_int2; // store into next and move on
*(hashtable_ptr ++) = some_double0; // << --- trouble
// ...
}
Accessing a double through a pointer to int causes undefined behavior.
In any case, unless you have a 10+ year old compiler it is almost
certain the compiler has done this optimization already (or a better
one even). If you're at this level of optimization then you should
probably look at the disasembly of the code to see what the compiler
generates and/or write your own assembly routine. Many processors have
vector instructions or similar stuff that could help you here.

Regards,
Bart.

Sep 7 '06 #2
<snip>

Oh and one more thing. Since you just seem to be copying members of a
POD structure then memcpy() is also acceptable, and it is probably
implemented optimally for your system as well.

Regards,
Bart.

Sep 7 '06 #3
Bart wrote:
[snip]
Accessing a double through a pointer to int causes undefined behavior.
But doesn't a cast alleviate this? I thought the compiler
would understand that I want to treat the binary representation
of a pointer to int like it was a pointer to double, so that
it would store the value correctly and then increment it
correctly. Won't this work?
In any case, unless you have a 10+ year old compiler it is almost
certain the compiler has done this optimization already (or a better
one even). If you're at this level of optimization then you should
probably look at the disasembly of the code to see what the compiler
generates and/or write your own assembly routine.
Yes and no. The compiler is a month-old intel compiler,
tuned to this particular architecture (Itanium 2), so you'd
expect it to be extremely aggresive, more so since this
architecture relies heavily on the compiler doing the
optimizations.

However, even with -O3 and other aggressive optimization
options I was able to outsmart the compiler in two places
by merely converting

array[index][0]=double0;
array[index][1]=double1;
array[index][2]=double2;

into

array_ptr = array[index];
*(array_ptr++)= ...;
*(array_ptr++)= ...;
*(array_ptr )=...;

as proven by profiler output. Writing my own assembly
routine is out of question -- this IA64 assembly output
is absolutely unreadable (at least to me, I only have
experience with x86 assembly) and looks like it is
quite heavily optimized already. Still, experience of the
past three days shows that translating indexing into
pointer arithmetics somehow makes the compiler perform
better still.
Many processors have
vector instructions or similar stuff that could help you here.
Yes, this processor in particular. My teammate managed
to vectorize the pow() and sqrt() operations which were
the previous bottleneck. What appears as the next bottleneck
is cache penalties for accessing elements of a large
(~1e6 doubles) array in an almost random order, many many
times. Hence I am trying to code a hashtable that would
store the values of most recently used elements in a
smaller table that would fit within the L2 cache.

Anyway, is there _really_ no way to access elements of
a struct using a single, advancing pointer? I suspect
some controller-programming C gurus would know a way?

TIA,
- J.
Sep 7 '06 #4
"Jacek Dziedzic" <jacek@no_spam. tygrys.no_spam. netschrieb im Newsbeitrag
news:3f******** *************** ****@news.chell o.pl...
>
Hi!

I'm trying to squeeze a few clock cycles from a tight
loop that profiling shows to be a bottleneck in my program.
I'm at a point where the only thing that matters is
execution speed, not style (within the loop, obviously).

The loop deals with an array:

// this is aligned at cache line boundaries
struct hash_t {
int id;
int next;
double d0;
double d1;
double d2;
} hashtable[HASH_MAX];

within the loop, whenever there is a hashtable miss I
need to store new values into hashtable[index].
Originally this looked like

if(...) {
hashtable[index].id=some_int;
hashtable[index].next=some_int2 ;
hashtable[index].d0=some_double 0;
hashtable[index].d1=some_double 1;
hashtable[index].d2=some_double 2;
}

Now... I'm trying to save a few cycles by doing something
along the lines of

if(...) {
// point to the first member
int *hashtable_ptr = reinterpret_cas t<int*&(hashtab le[index].id)
*(hashtable_ptr ++) = some_int; // store into id and move on
*(hashtable_ptr ++) = some_int2; // store into next and move on
*(hashtable_ptr ++) = some_double0; // << --- trouble
// ...
}

the trouble is that I'm working with a pointer to int
and I want to store a double and, later on, advance the
pointer not by sizeof(int) bytes, but by sizeof(double)
bytes. On my system sizeof(int) is 4, sizeof(double) is 8
and portability is not an issue.

I tried

*((reinterpret_ cast<double*>(h ashtable_ptr))+ +) = some_double0;

but I got an error:

"the result of this cast cannot be used as an lvalue".

Why's that?
The result of a cast is an rvalue, not an lvalue. Think of it as a temporary
variable. Then your statement becomes something like

double* temp = reinterpret_cas t<double*>(hash table_ptr);
*temp = some_double0;
temp++;

The problem is the final increment. It increments the temporary, not the
hashtable_ptr. To do that, you have to add an extra level of indirection

*((*reinterpret _cast<double**> (&hashtable_ptr ))++) = some_double0;

But before you try such nasty code, you should try something more readable:

if (...)
{
hash_t* ptr = &hashtable[index];
ptr->id = some_int;
ptr->next = some_int2;
ptr->d0 = some_double0;
...
}

If some_int, some_int2 etc. are local variables, which are computed as part
of the function, it might also improve speed if you replace all those
variables with a single, local instance of a hash_t struct. For most
compilers, code like

hash_t data;
data.id = ...
...

should be as fast as

int id, next;
double d0, d1, ...;
id = ...
...

But you could then copy the structure as a whole, like

if (...) hashtable[index] = data;

of even use memcpy, which still is much more readable than your pointer
tricks. Such tricks often even have negative effects on speed. Measure such
"improvemen t" very carefully and do it for every update of your compiler.
Even a compiler will understand (and optimize) simple code mush better than
tricky casts and pointer arithmetic.
I really need to force the compiler to treat
this pointer as a double* for a moment...
When you force a compiler to do something the way you want, you also force
it, not to do something it could do better than you do.
I realize I can
have two pointers to the same hashtable entry, one an int*
and one a double*, but I need to save every clock cycle I
can as this loop is executed trillions of times.

What's the usual procedure to iterate a pointer through
members of varying types? Perhaps it would be easier with
a char*, but that means advancing by 4 and 8 which,
I suppose, would be slower than plain ++? Or does it boil
to moving by 4 or 8 offsets at the assembly level too?
That depends on the hardware, your program is running on. Test it! And
remember, such tests are only valid for a single version of a compiler. You
have to test it again for each and every combination of hardware, operating
system and compiler. And the results may still depend on your code.

Heinz

Sep 7 '06 #5
Bart wrote:
<snip>

Oh and one more thing. Since you just seem to be copying members of a
POD structure then memcpy() is also acceptable, and it is probably
implemented optimally for your system as well.
Again, yes and no. The two things are that:
a) the source values that need to be stored into members
of the hash_t struct do not lie at subsequent addresses,
and if things work as expected they are in registers.
b) even though I believe memcpy() to be optimized to a single
cycle, the structure is so small (32 bytes) that I doubt
it would perform well, even if it is inlined.
Unfortunately this is not a case of copying multiple
entries of an array.

I guess b) may be disputed, but a) makes this a no-no.

thanks anyway,
- J.
Sep 7 '06 #6
Jacek Dziedzic wrote:
Bart wrote:
[snip]
Accessing a double through a pointer to int causes undefined behavior.

But doesn't a cast alleviate this? I thought the compiler
would understand that I want to treat the binary representation
of a pointer to int like it was a pointer to double, so that
it would store the value correctly and then increment it
correctly. Won't this work?
The cast only shuts up the compiler. It may work on your
implementation, but I was giving a general answer.
Anyway, is there _really_ no way to access elements of
a struct using a single, advancing pointer? I suspect
some controller-programming C gurus would know a way?
You can try using a char pointer that gets incremented by sizeof(int)
and sizeof(double). That would be pretty much equivalent to an
advancing pointer, although I can't say whether it's going to yield
faster code. Try it and see.

Regards,
Bart.

Sep 7 '06 #7
Heinz Ozwirk wrote:
>
The result of a cast is an rvalue, not an lvalue. Think of it as a
temporary variable. Then your statement becomes something like

double* temp = reinterpret_cas t<double*>(hash table_ptr);
*temp = some_double0;
temp++;

The problem is the final increment. It increments the temporary, not the
hashtable_ptr. To do that, you have to add an extra level of indirection
Right!
>
*((*reinterpret _cast<double**> (&hashtable_ptr ))++) = some_double0;
Yuck :)
But before you try such nasty code, you should try something more readable:

if (...)
{
hash_t* ptr = &hashtable[index];
ptr->id = some_int;
ptr->next = some_int2;
ptr->d0 = some_double0;
...
}
Yes, you were right! My incrementing a pointer combined with
heavy casting only made the matter worse (speedwise).
Your idea is slightly better (in terms of speed) than the
original code I posted.
If some_int, some_int2 etc. are local variables, which are computed as
part of the function, it might also improve speed if you replace all
those variables with a single, local instance of a hash_t struct. For
most compilers, code like

hash_t data;
data.id = ...
...

should be as fast as

int id, next;
double d0, d1, ...;
id = ...
...

But you could then copy the structure as a whole, like

if (...) hashtable[index] = data;

of even use memcpy, which still is much more readable than your pointer
tricks.
Unfortunately, the source part of the data copied is
in registers, so I guess memcpy is out of question,
especially since this struct is rather small (32 bytes)
and I don't work at contiguous batches of hash_t's
in one iteration.
Such tricks often even have negative effects on speed. Measure
such "improvemen t" very carefully and do it for every update of your
compiler. Even a compiler will understand (and optimize) simple code
mush better than tricky casts and pointer arithmetic.
It turns out you were right!
[snip]
thanks a lot,
- J.
Sep 7 '06 #8

Jacek Dziedzic wrote:
Hi!

I'm trying to squeeze a few clock cycles from a tight
loop that profiling shows to be a bottleneck in my program.
I'm at a point where the only thing that matters is
execution speed, not style (within the loop, obviously).

The loop deals with an array:

// this is aligned at cache line boundaries
struct hash_t {
int id;
int next;
double d0;
double d1;
double d2;
} hashtable[HASH_MAX];

within the loop, whenever there is a hashtable miss I
need to store new values into hashtable[index].
Originally this looked like

if(...) {
hashtable[index].id=some_int;
hashtable[index].next=some_int2 ;
hashtable[index].d0=some_double 0;
hashtable[index].d1=some_double 1;
hashtable[index].d2=some_double 2;
}
The compiler should do a good job of eliminating the common
subexpression hashtable[index], reducing it to a cached pointer value.
If you're worried that that doesn't happen, you can try doing that
reduction manually:

{
hash_t *tmp = &hashtable[index];
tmp->id = some_int;
tmp->next = some_int2;
...
}

That's about the best you can do.
if(...) {
// point to the first member
int *hashtable_ptr = reinterpret_cas t<int*&(hashtab le[index].id)
*(hashtable_ptr ++) = some_int; // store into id and move on
*(hashtable_ptr ++) = some_int2; // store into next and move on
*(hashtable_ptr ++) = some_double0; // << --- trouble
// ...
}
If the processor has an indexed addressing mode with displacement for
structure access, then doing this kind of thing won't help at all. All
it means is that you can use indirect addressing to fetch the data,
with no displacement.

In some instruction sets, it might even be the same instruction, with a
value of zero in the displacement field. So all you are doing is adding
the overhead of incrementing the base address.

Sep 7 '06 #9
"Jacek Dziedzic" <jacek@no_spam. tygrys.no_spam. netwrote in message
news:3f******** *************** ****@news.chell o.pl...
The loop deals with an array:

// this is aligned at cache line boundaries
struct hash_t {
int id;
int next;
double d0;
double d1;
double d2;
} hashtable[HASH_MAX];

within the loop, whenever there is a hashtable miss I
need to store new values into hashtable[index].
Originally this looked like

if(...) {
hashtable[index].id=some_int;
hashtable[index].next=some_int2 ;
hashtable[index].d0=some_double 0;
hashtable[index].d1=some_double 1;
hashtable[index].d2=some_double 2;
}

Now... I'm trying to save a few cycles by doing something
along the lines of

if(...) {
// point to the first member
int *hashtable_ptr = reinterpret_cas t<int*&(hashtab le[index].id)
*(hashtable_ptr ++) = some_int; // store into id and move on
*(hashtable_ptr ++) = some_int2; // store into next and move on
*(hashtable_ptr ++) = some_double0; // << --- trouble
// ...
}

the trouble is that I'm working with a pointer to int
and I want to store a double and, later on, advance the
pointer not by sizeof(int) bytes, but by sizeof(double)
bytes.
Do you have any evidence that successively incrementing hashtable_ptr will
be significantly faster than doing direct (constant offset) indexing? In
other words:

hash_t* hptr = &hashtable[index]; // or, equivalently,
hashtable+index
hptr->id = some_int;
hptr->next = some_int2;
hptr->d0 = some_double0;

and so on.

On most computers this will generate successive instructions that put hptr
in a register and specify appropriate offsets as part of each instruction,
and the processor will probably add those offsets to the register at least
as quickly as you can recompute an appropriate value for hashtable_ptr.
Plus you don't have to use reinterpret_cas t, which is almost never portable,
and you don't have to hope that the compiler won't put padding into your
structure that you didn't expect.

The main difference between my suggestion and your original version is that
I'm computing the address of hashtable[index] once, then reusing that
address. In fact, most optimizing compilers will do that for me, so it is
possible that the change will have no effect. Indeed, on many computers,
the execution time of the program fragment will depend more than anything
else on the number of memory references you make, which means that there may
not actually be anything you can do to speed up the program.
Sep 8 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
2100
by: John Burton | last post by:
I wrote a python program on windows which needs to listen for connections on a low numbered port which works fine on windows but on linux you need to be *root* in order to listen for connections on port numbers below 1024. I really don't want to run my program as root because that would give it unnecessary access to the whole of the system. Has anyone got any suggestion on the best way to allow my program to listen on those socket...
49
2562
by: Paul Rubin | last post by:
I've started a few threads before on object persistence in medium to high end server apps. This one is about low end apps, for example, a simple cgi on a personal web site that might get a dozen hits a day. The idea is you just want to keep a few pieces of data around that the cgi can update. Immediately, typical strategies like using a MySQL database become too big a pain. Any kind of compiled and installed 3rd party module (e.g....
1
6734
by: Vissu | last post by:
Hi All, We have one column with low cardinality, 4 or 5 unique values across 50 mil rows. Our query has this colunmn as a predicate. Binary index is not helping. I am tempted to create bitmap index but the general myth is there could be lot of contentions. We have a highly active OLTP system with concurrent DMLs.
0
1892
by: Andrew | last post by:
When will .NET have a low-pause-time garbage collector A low-pause-time garbage collector would greatly improve .NET's ability to serve as a platform for soft real-time systems. It doesn't have to be perfect. For example, I'd be happy with something where there was at most one pause per second, each pause was less than .2 seconds, and half the process's memory was inaccessible to the application due to garbage collection management It...
19
5883
by: Lorenzo J. Lucchini | last post by:
My code contains this declaration: : typedef union { : word Word; : struct { : byte Low; : byte High; : } Bytes; : } reg;
26
10882
by: Bruno Jouhier [MVP] | last post by:
I'm currently experiencing a strange phenomenon: At my Office, Visual Studio takes a very long time to compile our solution (more than 1 minute for the first project). At home, Visual Studio compiles the same solution much faster (about 10 seconds for the first project). My home computer is only marginally faster than the one I have at the office (P4 2.53 vs. P4 2.4, same amount of RAM). On the slow machine, the CPU usage is very low,...
5
2129
by: kevin.heart | last post by:
Hi all, How to implement such function for Linux/Unix? /* sample begins*/ #include "windows.h" .... MEMORYSTATUS stat; GlobalMemoryStatus(&stat); result = ((float)stat.dwAvailPageFile / stat.dwTotalPageFile) < 0.1;
2
4783
by: dunleav1 | last post by:
I have a many row and many column table that is in a 16K page size. I have four indexes on the table. I am running row compression on the table. The table does not have a primary key. The table does not have a clustered index. I ran a reorg on the table and the indexes. I ran runstats on the table and the indexes after the reorg. Three indexes on the table have an index cluster ratios of 99,99,100 respectively. The fourth index has a...
1
2755
by: Alexander Higgins | last post by:
>>Thanks for the response.... Point Taken but this is not the case. Thus, if a person writes a text file on her or his computer and does not use UNICODE to save it, the current code page is used. If this file is given to someone with some other current codepage, the file is not displayed correctly. Simply converting the file to Unicode will make the data display properly. When performing the encoding process the encoding will escape...
0
1918
by: WTH | last post by:
I ask because I've got a windows service I've written that manages failover and replication for our products (or even 3rd party applications) and it worked great right until I tested it (for ease of testing purposes) with Internet Explorer (iexplore.exe) - I was testing handling argument list buffer overflows. What I found with iexplore.exe is that because my windows service is running with high privileges (due to running under the local...
0
9587
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10211
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9993
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9863
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7406
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6672
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3958
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.