473,781 Members | 2,718 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
18 2248
Jacek Dziedzic wrote:
Now... I'm trying to save a few cycles by doing something
along the lines of
(...)
bytes. On my system sizeof(int) is 4, sizeof(double) is 8
and portability is not an issue.
Save a few cycles and sacrify portability? Write it in assembler. It will be
safer than ugly code, at least everyone that takes an eye in the code will
notice that is not portable.

--
Salu2
Sep 8 '06 #11
Jacek Dziedzic posted:
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
// ...
}

You're probably going the wrong way about this, but nonetheless...

char *p = (char*)hastable[index].id;

* (int*)p = some_int; p += sizeof some_int;
* (int*)p = some_int2; p += sizeof some_int2;
*(double*)p = some_double0; p += sizeof some_double0;

--

Frederick Gotham
Sep 8 '06 #12
Heinz Ozwirk posted:
The result of a cast is an rvalue, not an lvalue.

Yes, unless you cast to a reference type.

--

Frederick Gotham
Sep 8 '06 #13
Kaz Kylheku wrote:
>
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.
Yes, you were right, I only got the overhead.

It's weird then that the same (or similar) trick worked for
me a few hundred lines earlier, got to be a compiler quirk.

thanks,
- J.
Sep 8 '06 #14
Julián Albo wrote:
Jacek Dziedzic wrote:

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

(...)
>>bytes. On my system sizeof(int) is 4, sizeof(double) is 8
and portability is not an issue.

Save a few cycles and sacrify portability?
I think you're a little hasty in your conclusions. I don't
"sacrifice" portability, it's just not needed here. The program
is destined to run on a massively parallel machine, and
basically only on _this_ one machine, at least for the next
five years. The few cycles may mean days of computational
time of several tens of nodes saved, as this loop iterates
_trillions_ of times. Sure, perhaps in a few years this
computer will have become outdated and the program
will have to run on another machine with sizeof(int)==32
and sizeof(double)= =32, but this will be caught by an
assert in the init module that will ask somebody to fix
this. Fixing this would, in fact, be as easy as changing
an offset here or there in a clearly marked place.
Write it in assembler. It will be safer than ugly code
Recoding it in another assembly language in case of
a change of architecture won't be easy.
Furthermore I have to admit I can't code IA-64 assembly.
at least everyone that takes an eye in the code will
notice that is not portable.
Well, I think the two lines

// Warning: the following function is not portable.
// mind the offsets marked in *)

does the same job.

- J.
Sep 8 '06 #15
Andrew Koenig wrote:
[snip]
Yes, you were right.

thanks,
- J.
Sep 8 '06 #16
Frederick Gotham wrote:
Jacek Dziedzic posted:

>>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
// ...
}

You're probably going the wrong way about this, but nonetheless...

char *p = (char*)hastable[index].id;

* (int*)p = some_int; p += sizeof some_int;
* (int*)p = some_int2; p += sizeof some_int2;
*(double*)p = some_double0; p += sizeof some_double0;
Thanks. That's the way I tried and, as others have warned me,
I only got the overhead.

- J.
Sep 8 '06 #17
Jacek Dziedzic wrote:
>Save a few cycles and sacrify portability?
I think you're a little hasty in your conclusions. I don't
"sacrifice" portability, it's just not needed here. The program
is destined to run on a massively parallel machine, and
basically only on _this_ one machine, at least for the next
five years.
Then tell me in 2012 if you sacrificed something or not.
The few cycles may mean days of computational
time of several tens of nodes saved, as this loop iterates
_trillions_ of times.
I think you're a little hasty in your conclusions. I did not say that the
few cycles implied a little gain.
Write it in assembler. It will be safer than ugly code
Recoding it in another assembly language in case of
a change of architecture won't be easy.
I doubt that recoding obfuscated nonportable C++ will be.

--
Salu2
Sep 8 '06 #18
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
// ...
}

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...
1. Try keeping everything in units of "struct hash_t".
Fill in an instance before hashing. If you need to
insert into the table, just copy the item:
struct hash_t new_item;
// ...
hashtable[index] = new_item;
This has the benefit of letting the compiler figure
out the best way to copy the data. The best method
may be item per item, block / string copy, or DMA
to cite a few. Worst case, you could call an
implementation specific function:
implementation_ memcpy(&hashtab le[index],
&new_item,
sizeof(new_item ));

2. Are all the items in "struct hash_t" needed to make
the hash table work?
Perhaps just the key and a pointer to data located
elsewhere. Thus only a small amount of data (the
key and pointer) are moved around in the table.
Most computer time is spent searching and sorting,
not by deferencing to get at value of a <key, value>
pair.

3. Remove operations not needed. Does the hash table
need to be used as often?

--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.l earn.c-c++ faq:
http://www.comeaucomputing.com/learn/faq/
Other sites:
http://www.josuttis.com -- C++ STL Library book
http://www.sgi.com/tech/stl -- Standard Template Library

Sep 9 '06 #19

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

Similar topics

6
2101
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
2565
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
6735
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
1893
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
5886
by: Lorenzo J. Lucchini | last post by:
My code contains this declaration: : typedef union { : word Word; : struct { : byte Low; : byte High; : } Bytes; : } reg;
26
10884
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
2130
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
2756
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
9474
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
10308
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
10076
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
9939
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...
0
8964
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6729
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
5507
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3633
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2870
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.