473,394 Members | 1,674 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

how to avoid loop overhead of for(), while()

I want to time my matrix multiply code (in MFLOPS). I want to run the
code 100,000 times or some other big number.
This can be done 2 ways (for and while loops):

timer1 = time(NULL);
for(n = 0; n < 100000; n++)
mm();
timer2 = time(NULL);

exectime = difftime(timer2, timer1);

However, this means there will be a comparison of "n" on each
iteration and increment operation each time. I want to avoid this, if
you use while() same problem.
So is there someway to avoid the loop overhead, i.e. tell it:
do 100000 times{
mm
}
Pushkar Pradhan
Nov 13 '05 #1
17 5876
Pushkar Pradhan wrote:
timer1 = time(NULL);
for(n = 0; n < 100000; n++)
mm();
timer2 = time(NULL);

exectime = difftime(timer2, timer1);

However, this means there will be a comparison of "n" on each
iteration and increment operation each time. I want to avoid this, if
you use while() same problem.
So is there someway to avoid the loop overhead, i.e. tell it:
do 100000 times{
mm
}
Pushkar Pradhan


ehm... and how exactly do you think that statement would be implemented
if it existed apart from keeping a counter initialized to 100000 and
decremented and tested for equality with 0 for each loop? do you know of
any magic that the rest of us miss?

-- Nuclear / the Lab --

Nov 13 '05 #2
Pushkar Pradhan wrote:
I want to time my matrix multiply code (in MFLOPS). I want to run the
code 100,000 times or some other big number.
This can be done 2 ways (for and while loops):

timer1 = time(NULL);
for(n = 0; n < 100000; n++)
mm();
timer2 = time(NULL);

exectime = difftime(timer2, timer1);

However, this means there will be a comparison of "n" on each
iteration and increment operation each time. I want to avoid this, if
you use while() same problem.
A good compiler should be (and usually is) smart enough to know about
the comparisons and increments and optimize this away. Even if it
doesn't, these comparisons and integer increments hardly ever take up
extra CPU cycles compared to what your mm() function will be taking
(flops will take more cycles and so while a single flop is underway, the
processor will be able to do a number of integer operations and
comparisons). Effectively, there will be *no* overhead involved in using
a loop for timing your function. Literally *all* scientific code there
is out there uses loops for measuring performance of functions. You
should have no concern about overheads at all.

So is there someway to avoid the loop overhead, i.e. tell it:
do 100000 times{
mm
}
Even if there was a way to do this, this would require an implicit
comparison on the number of times the code has been executed, and
keeping a count by incrementing it each time, thus having the same effect.

-Rick

Pushkar Pradhan


Nov 13 '05 #3
Run two routines measuring the time respectively.

1. first routine
timer1 = time(NULL);
for(n = 0; n < 100000; n++)
mm();
timer2 = time(NULL);

time1 = difftime(timer2, timer1);

2. second routine - n must be declared with the volatile type qualifier
timer1 = time(NULL);
for(n = 0; n < 100000; n++);

timer2 = time(NULL);

time2 = difftime(timer2, timer1);

The net time to call mm() 100000 times could be calculated....
exectime = time2 - time1.

But the results may differ every time you run.
"Pushkar Pradhan" <pu*******@hotmail.com> wrote in message
news:7f*************************@posting.google.co m...
: I want to time my matrix multiply code (in MFLOPS). I want to run the
: code 100,000 times or some other big number.
: This can be done 2 ways (for and while loops):
:
: timer1 = time(NULL);
: for(n = 0; n < 100000; n++)
: mm();
: timer2 = time(NULL);
:
: exectime = difftime(timer2, timer1);
:
: However, this means there will be a comparison of "n" on each
: iteration and increment operation each time. I want to avoid this, if
: you use while() same problem.
: So is there someway to avoid the loop overhead, i.e. tell it:
: do 100000 times{
: mm
: }
: Pushkar Pradhan

Nov 13 '05 #4
Kyle S. Shim wrote:
1. first routine
timer1 = time(NULL);
for(n = 0; n < 100000; n++)
mm();
timer2 = time(NULL);

time1 = difftime(timer2, timer1);


/* highrestime is assumed to be an implementation of a highresolution timer
*/
totaltime = 0;
for ( ... )
{
timer = highrestime(NULL);
mm;
totaltime += highrestime(NULL) - timer;
}

of course you would need a real high res timer, or this still wouldn't work
properly.

Good luck,

--
Martijn
http://www.sereneconcepts.nl
Nov 13 '05 #5
# However, this means there will be a comparison of "n" on each
# iteration and increment operation each time. I want to avoid this, if
# you use while() same problem.
# So is there someway to avoid the loop overhead, i.e. tell it:
# do 100000 times{
# mm
# }

There may be vector hardware on your machine, but C doesn't have a standard way to
access that. Some variants of C do, C* I think is one, as well other languages like
Fortran 90.

--
Derk Gwen http://derkgwen.250free.com/html/index.html
Elvis was an artist. But that didn't stop him from joining the service
in time of war. That's why he is the king, and you're a shmuck.
Nov 13 '05 #6
"Pushkar Pradhan" <pu*******@hotmail.com> wrote in message
news:7f*************************@posting.google.co m...
I want to time my matrix multiply code (in MFLOPS). I want to run the
code 100,000 times or some other big number.
This can be done 2 ways (for and while loops):

timer1 = time(NULL);
for(n = 0; n < 100000; n++)
mm();
timer2 = time(NULL);

exectime = difftime(timer2, timer1);

However, this means there will be a comparison of "n" on each
iteration and increment operation each time. I want to avoid this, if
you use while() same problem.
So is there someway to avoid the loop overhead, i.e. tell it:
do 100000 times{
mm
}
Pushkar Pradhan


Despite the fact that the loop counting you show
above will not likely have a noticeable impact on
your timing, I had fun writing this:
#include <stdio.h>
#include <stdlib.h>

#define PROTOTYPE "void mm();\n"
#define CALL " mm();\n"
#define ITERATIONS 100000

int main()
{
const char *code[] =
{
"#include <stdio.h>\n",
"#include <time.h>\n",
"\n",
PROTOTYPE,
"\n",
"int main(void)\n",
"{\n",
" time_t timer1 = time(NULL);\n",
" time_t timer2;\n",
" double exectime = 0;\n",
"\n",
"@",
"\n",
" timer2 = time(NULL);\n",
" exectime = difftime(timer2, timer1);\n",
" printf(\"Execution time %f seconds\\n\", exectime);\n",
" return 0;\n",
"}\n"
};

const int ret[] = {EXIT_SUCCESS, EXIT_FAILURE};

const size_t lines = sizeof code / sizeof *code;
size_t line = 0;

const unsigned long iters = ITERATIONS;
unsigned long iter = 0;

int call = 0;
int err = 0;

FILE *file = fopen("timeit.c", "w");

if(file)
for(line = 0; line < lines; ++line)
{
if(call = (*(code[line]) == '@'))
{
for(iter = 0; iter < iters; ++iter)
if(fputs(CALL, file) < 0)
break;
}
else
if(fputs(code[line], file) < 0)
break;

if(call && iter < iters)
break;
}
else
fprintf(stderr, "%s\n", "Cannot open output");

if(file && fclose(file) || (err = line < lines))
fprintf(stderr, "%s (line %lu)\n",
"Error writing output", (unsigned long)++line);

return ret[err];
}
Compile, link, and run this, compile the output
(file "timeit.c"), and link it with your 'mm()'
function. Of course you're still paying time
overhead for the call to 'mm()'. If you have
the source, you can apply this same method,
replacing the call to 'mm()' with its source,
and make a *really* big "timeit.c" file.

:-)

-Mike

Nov 13 '05 #7
pu*******@hotmail.com (Pushkar Pradhan) writes:
I want to time my matrix multiply code (in MFLOPS). I want to run the
code 100,000 times or some other big number.
This can be done 2 ways (for and while loops):

timer1 = time(NULL);
for(n = 0; n < 100000; n++)
mm();
timer2 = time(NULL);

exectime = difftime(timer2, timer1);

However, this means there will be a comparison of "n" on each
iteration and increment operation each time. I want to avoid this, if
you use while() same problem.
So is there someway to avoid the loop overhead, i.e. tell it:
do 100000 times{
mm
}


There's an optimization called loop unrolling that can eliminate some
of the overhead at the expense of larger code. For example:

timer1 = time(NULL);
for(n = 0; n < 10000; n++) {
mm();
mm();
mm();
mm();
mm();
mm();
mm();
mm();
mm();
mm();
}
timer2 = time(NULL);

exectime = difftime(timer2, timer1);

Consult your compiler's documentation; it's quite possible that you
can persuade the compiler to do this for you. (gcc, for example, as a
"-funroll-loops" option.)

--
Keith Thompson (The_Other_Keith) ks*@cts.com <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
Nov 13 '05 #8
"Kyle S. Shim" <tw********@korea.com> wrote in message news:<bl**********@news1.kornet.net>...
Run two routines measuring the time respectively.

1. first routine
timer1 = time(NULL);
for(n = 0; n < 100000; n++)
mm();
timer2 = time(NULL);

time1 = difftime(timer2, timer1);

2. second routine - n must be declared with the volatile type qualifier
I am not sure if declaring n to be a 'volatile' would make sure that n
would be incremented precisely 100,000 times rather than the block

for ( n = 0; n < 100000; n ++ )

being ignored completly.

timer1 = time(NULL);
for(n = 0; n < 100000; n++);

timer2 = time(NULL);

time2 = difftime(timer2, timer1);

The net time to call mm() 100000 times could be calculated....
exectime = time2 - time1.

But the results may differ every time you run.


--
Imanpreet Singh Arora
imanpreet_arora AT yahoo DOT co DOT in
Nov 13 '05 #9
Minti wrote:
2. second routine - n must be declared with the volatile type
qualifier


I am not sure if declaring n to be a 'volatile' would make sure that n
would be incremented precisely 100,000 times rather than the block

for ( n = 0; n < 100000; n ++ )

being ignored completly.


If you'd change the loop to call an empty function (and make sure the
compiler doesn't optimize it out), you would also take care of the overhead
of calling the function.

--
Martijn
http://www.sereneconcepts.nl
Nov 13 '05 #10
Mike Wahler wrote:
[ snip ]
Compile, link, and run this, compile the output
(file "timeit.c"), and link it with your 'mm()'
function. Of course you're still paying time
overhead for the call to 'mm()'. If you have
the source, you can apply this same method,
replacing the call to 'mm()' with its source,
and make a *really* big "timeit.c" file.

:-)

-Mike


Doggone it, that was going to be my answer. :-)
--
Joe Wright http://www.jw-wright.com
"Everything should be made as simple as possible, but not simpler."
--- Albert Einstein ---
Nov 13 '05 #11
On Thu, 02 Oct 2003 09:40:39 GMT, Keith Thompson <ks*@cts.com> wrote:
However, this means there will be a comparison of "n" on each
iteration and increment operation each time. I want to avoid this, if
you use while() same problem.
So is there someway to avoid the loop overhead, i.e. tell it:
do 100000 times{
mm
}


There's an optimization called loop unrolling that can eliminate some
of the overhead at the expense of larger code. For example:


Yes. The other proposals all have a problem in that the processor's
handling of cache will probably have more effect than any other
factor. (In spite of the fact that cache isn't topical in c.l.c <g>.)
Completely unrolling the loop minimizes both the cache effects and the
overhead.

--
Al Balmer
Balmer Consulting
re************************@att.net
Nov 13 '05 #12
Pushkar Pradhan wrote:

I want to time my matrix multiply code (in MFLOPS). I want to run the
code 100,000 times or some other big number.
This can be done 2 ways (for and while loops):

timer1 = time(NULL);
for(n = 0; n < 100000; n++)
mm();
timer2 = time(NULL);

exectime = difftime(timer2, timer1);

However, this means there will be a comparison of "n" on each
iteration and increment operation each time. I want to avoid this, if
you use while() same problem.
So is there someway to avoid the loop overhead, i.e. tell it:
do 100000 times{
mm
}


No problem:

timer1 = time(NULL);
mm(); /* 1 */
mm(); /* 2 */
/* 99997 additional lines left as an exercise */
mm(); /* 100000 */
timer2 = time(NULL);

However, it's probably not necessary to go to this much
trouble. mm() will probably take a good deal more time than
the loop's increment-test-branch overhead, so the presence
of the latter won't contaminate your timings noticeably. In
the more general case where mm() is replace with something
very fast, possibly on the same order of speed as the loop
machinery, you can time the loop with and without the "guts"
and subtract one timing from the other.

--
Er*********@sun.com
Nov 13 '05 #13
nrk
Mike Wahler wrote:
#define ITERATIONS 100000
<snip>
const unsigned long iters = ITERATIONS;


Just out of curiosity, why the #define and then the const constant as well?
Is this for one of those situations where the value of PI might change? :-)

-nrk.
Nov 13 '05 #14
"nrk" <nr*******@hotmail.com> wrote in message
news:bl**********@mozo.cc.purdue.edu...
Mike Wahler wrote:
#define ITERATIONS 100000
<snip>


Note: (30 lines were snipped)
const unsigned long iters = ITERATIONS;


Just out of curiosity, why the #define and then the const constant as

well? Is this for one of those situations where the value of PI might change?

:-)

No, it's so I can quickly change the value, not
needing to hunt for it, by having the #define
at the top of the file. In a "real" program,
I'd have probably put it in a header, but that
seems silly for a single macro in a toy program.

-Mike
Nov 13 '05 #15
nrk
Mike Wahler wrote:
"nrk" <nr*******@hotmail.com> wrote in message
news:bl**********@mozo.cc.purdue.edu...
Mike Wahler wrote:
> #define ITERATIONS 100000


<snip>


Note: (30 lines were snipped)
> const unsigned long iters = ITERATIONS;


Just out of curiosity, why the #define and then the const constant as

well?
Is this for one of those situations where the value of PI might change?

:-)

No, it's so I can quickly change the value, not
needing to hunt for it, by having the #define
at the top of the file. In a "real" program,
I'd have probably put it in a header, but that
seems silly for a single macro in a toy program.

-Mike


Ok, Now I am confused. What is the utility of the const constant? Can't you
encode the type information in the #define as well? I know I must be
missing something, but I won't rest till someone beats me with a wet noodle
and makes me realize what it is :-)

-nrk.
Nov 13 '05 #16

"nrk" <nr*******@hotmail.com> wrote in message
news:bl**********@mozo.cc.purdue.edu...
Mike Wahler wrote:
"nrk" <nr*******@hotmail.com> wrote in message
news:bl**********@mozo.cc.purdue.edu...
Mike Wahler wrote:

> #define ITERATIONS 100000

<snip>
Note: (30 lines were snipped)
> const unsigned long iters = ITERATIONS;

Just out of curiosity, why the #define and then the const constant as

well?
Is this for one of those situations where the value of PI might change?

:-)

No, it's so I can quickly change the value, not
needing to hunt for it, by having the #define
at the top of the file. In a "real" program,
I'd have probably put it in a header, but that
seems silly for a single macro in a toy program.

-Mike


Ok, Now I am confused. What is the utility of the const constant?


It's a real object which can be type-checked.
Can't you
encode the type information in the #define as well?

Yes.
I know I must be
missing something, but I won't rest till someone beats me with a wet noodle and makes me realize what it is :-)


The constant could indeed have been expressed with a macro,
but my ingrained 'coding practice' causes me to use a const
object instead.

-Mike
Nov 13 '05 #17
nrk
Mike Wahler wrote:

<snip>
I know I must be
missing something, but I won't rest till someone beats me with a wet

noodle
and makes me realize what it is :-)


The constant could indeed have been expressed with a macro,
but my ingrained 'coding practice' causes me to use a const
object instead.


Thank you. I know that this is just a style issue, but I am trying to build
up a case in favor of one or the other for my own coding style. So, if
you'd be so kind as to provide some of your reasons for preferring this
style...

-nrk.
Nov 13 '05 #18

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

Similar topics

47
by: Mountain Bikn' Guy | last post by:
Take some standard code such as shown below. It simply loops to add up a series of terms and it produces the correct result. // sum numbers with a loop public int DoSumLooping(int iterations) {...
21
by: Alo Sarv | last post by:
Hi From what I have understood from various posts in this newsgroup, writing event loops pretty much comes down to this: while (true) { handleEvents(); sleep(1); // or _sleep() or...
22
by: T.S.Negi | last post by:
Hi All, I want to avoid using cursors and loops in stored procedures. Please suggest alternate solutions with example (if possible). Any suggestion in these regards will be appreciated. ...
5
by: John Dumais | last post by:
Hello, I have been trying to figure out how to write an array of doubles (in this specific case) to a binary stream without using a loop. What I have been doing is... foreach(double d in...
5
by: Javaman59 | last post by:
I have a real-time simulation where the logic flows most easily with a busy while loop... while (continueFlagSet) { if (EventDue) ProcessNextEvent } Now, is there any thing to be concerned...
2
by: Praveen_db2 | last post by:
Hi All db2 V 8.1.3 Windows I have an application which processes some rows using an SP.There are 2 approaches to this issue. 1) I can call the SP once and pass all the rows together as CLOB.(Rows...
10
by: Lyle Fairfield | last post by:
II first noticed this phenomenon in Access 2003. Simply stated it is: The second loop is faster than the first loop. That is if we test: Not (a Or b) against (Not a) And (Not b) in a loop of...
5
by: StephQ | last post by:
This is from a thread that I posted on another forum some days ago. I didn't get any response, so I'm proposing it in this ng in hope of better luck :) The standard explanation is that pointer...
5
by: Sune | last post by:
Hi all, I want to make data stored in-memory (not disk) available to several processes. My concern is that poorly written C applications with dangling pointers may(will) damage the data in this...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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...

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.