473,847 Members | 1,457 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Indexing an array

I hope this is the correct group. It came out a doubt about speed
when indexing an array in the following way:

for a given pointer p, p[0] contains an address and p[1] an offset.
I must return the content of the address plus the offset.. Which way
is faster and more portable?

1.- *( ((unsigned int*)*p) + *(p+1) ) ;
2.- ((unsigned int*)*p)[ *(p+1) ] ;
3.- *((unsigned int*)(*p ++ + *p)) ;

thanks!

Jul 17 '07 #1
6 1410
di****@gmail.co m wrote:
I hope this is the correct group. It came out a doubt about speed
when indexing an array in the following way:

for a given pointer p, p[0] contains an address and p[1] an offset.
Bleagh. That means you're going to have to play casting games.
Why not have `p` point to a struct with a pointer and an offset
in it, nicely typed? What's the problem context?
I must return the content of the address plus the offset.. Which way
is faster and more portable?

1.- *( ((unsigned int*)*p) + *(p+1) ) ;
2.- ((unsigned int*)*p)[ *(p+1) ] ;
3.- *((unsigned int*)(*p ++ + *p)) ;
They're all horrible, whatever their speed.

(3) is the worst, since it falls foul of undefined behaviour:
you modify `p` /and/ independently read it. Don't do that.

(1) and (2) are exactly equivalent in terms of C semantics,
since if `p` is a pointer and `i` is an int[eger] the
expression `p[i]` is defined to be/mean the same as `*(p+i)`.
Indeed we can have

2.5- ((unsigned int*) *p)[p[1]]

(I leave out the semicolon because this presumably isn't
supposed to be a statement; if it were, you could replace
it with `{}` with the same effect.)

But, as I say above, I wouldn't use a pointer that you're
going to pretend points to different types. I'd use a
(pointer to) struct and write something like:

0.- p->base[p->offset]

Unless, given the context, something even better suggested
itself.

--
Bleagh Hedgehog
Notmuchhere: http://www.electrichedgehog.net/

Jul 17 '07 #2

<di****@gmail.c omwrote in message
news:11******** **************@ g37g2000prf.goo glegroups.com.. .
>I hope this is the correct group. It came out a doubt about speed
when indexing an array in the following way:

for a given pointer p, p[0] contains an address and p[1] an offset.
I must return the content of the address plus the offset.. Which way
is faster and more portable?

1.- *( ((unsigned int*)*p) + *(p+1) ) ;
2.- ((unsigned int*)*p)[ *(p+1) ] ;
3.- *((unsigned int*)(*p ++ + *p)) ;
If you've go something quirky like that, make explicit what you are doing.

unsigned int *ptr = p[0];
int index = (int) p[1];
unsigned int x = ptr[index];

any modern compiler can microptimise expressions very easily to eliminate
the intermediates which are needed for readability, not storage.

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm
Jul 17 '07 #3
On Jul 17, 7:22 pm, Chris Dollin <e...@electrich edgehog.netwrot e:
They're all horrible, whatever their speed.
Lol... you put an smile with your expresion ;)
(3) is the worst, since it falls foul of undefined behaviour:
you modify `p` /and/ independently read it. Don't do that.
I agree with you in all. I am trying to meassure the program to
see which one is faster. Even the one you suggested about using
a nice casting to an struct. I will comment the results.
(1) and (2) are exactly equivalent in terms of C semantics,
since if `p` is a pointer and `i` is an int[eger] the
expression `p[i]` is defined to be/mean the same as `*(p+i)`.
yeah, but p[i] should be faster (in Intel) than *(p+i),
because p[i] is a machine instruction which can use preload,
while p + i needs from 2 instructions at least (all this
is assuming compiler does ZERO optimizations).
0.- p->base[p->offset]
My fear is that taking structs everywhere (just for a casting!)
will make code even more terrible!. The expresions I wrote are
expanded inline, etc etc, which complex the tasks of looking
how they are translated in each use.
Unless, given the context, something even better suggested
itself.
Imagine it was an exam question ;)

Thanks for your answer, I appreciate it.

Jul 19 '07 #4
On Jul 17, 10:28 pm, "Malcolm McLean" <regniz...@btin ternet.com>
wrote:
>
If you've go something quirky like that, make explicit what you are doing.

unsigned int *ptr = p[0];
int index = (int) p[1];
unsigned int x = ptr[index];
I did not know compiler will work so fine. But if the compiler does
not
support inlined functions, how will you write it in a "#define"?

Jul 19 '07 #5
di****@gmail.co m wrote:
On Jul 17, 7:22 pm, Chris Dollin <e...@electrich edgehog.netwrot e:
>They're all horrible, whatever their speed.

Lol... you put an smile with your expresion ;)
I'm serious that they're all horrible, if it's supposed to be
code that people read & write.
>(3) is the worst, since it falls foul of undefined behaviour:
you modify `p` /and/ independently read it. Don't do that.

I agree with you in all. I am trying to meassure the program to
see which one is faster. Even the one you suggested about using
a nice casting to an struct.
I did /not/ suggest any /casting/ to a struct. I suggested /using/
a struct.
I will comment the results.
>(1) and (2) are exactly equivalent in terms of C semantics,
since if `p` is a pointer and `i` is an int[eger] the
expression `p[i]` is defined to be/mean the same as `*(p+i)`.

yeah, but p[i] should be faster (in Intel) than *(p+i),
because p[i] is a machine instruction which can use preload,
while p + i needs from 2 instructions at least (all this
is assuming compiler does ZERO optimizations).
Compilers don't do ZERO optimisations nowadays. Turning the
code sequence for p, i, +, * into the same code sequence as
p, i, [] is the kind of thing that peephole optimisers could
do thirty years ago on 16-bit processors.

If you're interested in your code executing fast, you /will/ ask
the compiler to turn its optimisers on (up).
> 0.- p->base[p->offset]

My fear is that taking structs everywhere (just for a casting!)
There. Is. No. Casting. Here.
will make code even more terrible!. The expresions I wrote are
expanded inline, etc etc, which complex the tasks of looking
how they are translated in each use.
Ahhhh -- let me guess; this is supposed to be the compiled output
of something? `p` is a pointer into a fake machine store, hence
the type games? If so, then might be better off using a union:

typedef union machine_word Word;

union machine_word
{
Word *pointer;
int integer;
... other possibilities ...
};

...

Word *p;

...

p[0].pointer[p[1].integer]

But it depends. /Please/ tell us the context of the question:
it makes a difference. (In a compiler/interpreter I wrote
some time ago, I too had to play silly games moving between
types. I believe the games were justfied -- in context. But
they might not have been; several years later, I hope my
coding has continued to improve.)
>Unless, given the context, something even better suggested
itself.

Imagine it was an exam question ;)
Imagine the examiner having an epiphany and, instead of setting
the exam, taking a holiday in the Lake District.
Thanks for your answer, I appreciate it.
You're welcome.

--
Hewlett-Packard Limited Cain Road, Bracknell, registered no:
registered office: Berks RG12 1HN 690597 England

Jul 19 '07 #6
On Jul 18, 5:47 am, Barry Schwarz <schwa...@doezl .netwrote:
Speed is irrelevant if the result is incorrect.
So fully agree!
What are the units for offset? If it is bytes, your code is
incorrect because it computes the wrong address.
p is unsigned int *. The units of the offest are in unsigned int.
Is the value to be extracted truly an unsigned int? Is the
value of p[0] correctly aligned for an unsigned int?
yes to all
>
What is the type of p? Since you don't cast the expression
*(p+1), I expect it is something similar to int*.
mmm I dont cast it but the result is and unsigned int*. Sorry, I
forgot
to say the pointer type :((
Are you absolutely positive that the pointer value in p[0] and
the offset in p[1] have the same size?
Absolutely. In fact the invention works, there is not better
demostration ;)
Does you implementation guarantee that converting an int (*p)
to a pointer will have the
Yeah, that is precisely the trick hehe
Just out of curiosity, how did you end up with such a sorry state?
Implemeting an Abstract Machine (for Prolog, nor for Java) that
takes only 2 pages (of 4Kb) of memory and goes between 8 and 100
times faster (in the set of benchmarks I have, but we will see
in the rest of programs) than conventional abstract machines ;)

In AM all memory is plain and the program executed has no
types at all (they are created on run-time). Even internal
structs of the AM are not too typed. You only know that in a
certain address of memory there is another address of memory
that cointains the data you want... etc etc, and you only know
that in run-time, that is because an "int" can be a pointer,
a number, a char...
Converting an int to a pointer is guaranteed non-portable.
I dont guess any reason for that... but I believe you. Thanks
for the info, I hope not to run into a wall too hard when
porting it to other architectures.
Remove del for email
emmm, is this your quote? Else I did not get the meaning
of this sentence.
Jul 19 '07 #7

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

Similar topics

21
4341
by: Hilde Roth | last post by:
This may have been asked before but I can't find it. If I have a rectangular list of lists, say, l = ,,], is there a handy syntax for retrieving the ith item of every sublist? I know about for i in l] but I was hoping for something more like l. Hilde
6
2752
by: Michael Drumheller | last post by:
(If you're not interested in NumArray, please skip this message.) I am new to NumArray and I wonder if someone can help me with array-indexing. Here's the basic situation: Given a rank-2 array (i.e., a matrix) it seems to be trivial, with array indexing, to extract a subset of its *columns*. But it does not seem to be trivial to extract a subset of its *rows*. The code snippet below describes the problem (if it really is a problem)...
1
2219
by: jon wayne | last post by:
Hi Am trying to replace the classic switch case construct (am workng on a telecom stack devlpmnt)with an array of function ptrs. The problm am facing is that of indexing. - the case vals can be any of 0- 0xFF(1 byte long) - but unfortunately as of now I just need to use about 15 of 'em. In the sense I can't just make an array of function ptrs - coz the case vals I need to use right now are high up in the range.
10
4668
by: Tamir Khason | last post by:
I have a pointer to array and I want to apply indexing to this Array so I have function (name it IntPrt Func) to go to certain member I can use (as C++) Func, but in C# I recieve an error "Cannot apply indexing with to an expression of type 'System.IntPtr'". How to get rid of it? TNX --
0
4242
by: Chung Leong | last post by:
Here's a short tutorial on how to the OLE-DB extension to access Windows Indexing Service. Impress your office-mates with a powerful full-text search feature on your intranet. It's easier than you think. First, download and install the extension (http://sourceforge.net/project/showfiles.php?group_id=171247&package_id=198554). Simply unzip the file and copy the correct version of php_oledb.dll into the PHP extensions folder. Then add the...
26
410
by: jacob navia | last post by:
Suppose an implementation where sizeof int == 4 sizeof void * == 8 sizeof long long == 8 When indexing an array array this would mean that arrays are limited to 2GB. To overcome this,
4
1469
by: Grace Fang | last post by:
Hi, I am writing code to sort the columns according to the sum of each column. The dataset is huge (50k rows x 300k cols), so i need to read line by line and do the summation to avoid the out-of-memory problem. But I don't know why it runs very slow, and part of the code is as follows. I suspect it's because of array index, but not sure. Can anyone point out what needs to be modified to make it run fast? thanks in advance!
4
11614
by: Emin | last post by:
Dear Experts, How much slower is dict indexing vs. list indexing (or indexing into a numpy array)? I realize that looking up a value in a dict should be constant time, but does anyone have a sense of what the overhead will be in doing a dict lookup vs. indexing into a list? Some ad hoc tests I've done indicate that the overhead is less than 15% (i.e., dict lookups seem to take no more than 15% longer than indexing into a list and there...
4
26528
by: Chiefy | last post by:
C# APP Basically i am trying to use indexing on an array that i have fed into a method as its parameter. Here is a simplified version of my code. public void Inputs(string path) { string line; line = inputstream.ReadToEnd(); string words; char seperators = { '\t', '\n' }; words = line.Split(seperators);
3
6845
by: Rüdiger Werner | last post by:
Hello! Out of curiosity and to learn a little bit about the numpy package i've tryed to implement a vectorised version of the 'Sieve of Zakiya'. While the code itself works fine it is astounding for me that the numpy Version is almost 7 times slower than the pure python version. I tryed to find out if i am doing something wrong but wasn't able to find any answer.
0
9892
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
9734
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
10653
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10718
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
9490
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
5725
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5915
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4540
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
3
3168
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.