Programming Challenge 1

Started by
50 comments, last by Zahlman 16 years, 8 months ago
Optimize the following code and give detailed reason.

// Initialize iloveseven to an array of 7s
int i, j;
int iloveseven[1024][1024];

for(i = 0; i < 1024; i++) for(j = 0; j < 1024; j++) iloveseven[j] = 7;

Hints: obviously the code has no logical problem. Try to think in a remote area of computer programming. EDIT: more hints: paging, int has size of 4 bytes EDIT2: Check answer on page 2 of this thread [Edited by - TimChan on August 15, 2007 8:43:17 PM]
Advertisement
You could pre-increment for a start :P. Though the compiler most likely sorts that out.
Quote:Original post by Dave
You could pre-increment for a start :P. Though the compiler most likely sorts that out.

Your answer is correct. But there is another answer.
Optimize for what — space? Performance?

First thought (probably not what you're looking for, though; technically, I guess it also doesn't function in exactly the same way in that it isn't possible to overflow):

template <typename T> class FilledContainer{    T fill;public:    FilledContainer(T Fill) : fill(Fill)    {}    T operator[](unsigned long)    {        return fill;    }};// ...FilledContainer<int> foo(7);
[TheUnbeliever]
iloveseven[j] has better cache coherency, since i changes less frequently than j.

TheUnbeliever: That's cute, I like that.
cant you just memset that entire block of memory?
Pain is Inevitable, Suffering is Optional.Unknown
Can you go from i = 0 to i = 1048576 and hop through *iloveseven setting each to 7?

or just iloveseven[1024][1024] = {7}; //can't remember if that works how I'm thinking it does
// Initialize iloveseven to an array of 7sshort i, j;char iLoveseven[1024][1024];for(i = -1; i < 1024; ++i) for(j = -1; j < 1024; ++j) iLoveseven[j] = 7;

Progress is born from the opportunity to make mistakes.

My prize winning Connect 4 AI looks one move ahead, can you beat it? @nickstadb
You are misusing the cache.
Try this:
for(j = 0; j < 1024; j++) for(i = 0; i < 1024; i++) iloveseven[j] = 7;
Quote:Original post by jpetrie
iloveseven[j] has better cache coherency, since i changes less frequently than j.

TheUnbeliever: That's cute, I like that.

So what exactly cache coherency means? Your answer is correct and expected but I think the explanation is incomplete.

This topic is closed to new replies.

Advertisement