Ok, so I'm trying to prove to my teacher that Div and Mod isn't always the best way to solve things. So i created this tiny program, held entirely in main.cpp :

//Project: Mod_Efficiency
//Author : Kyle Wesley
//Descrip: This was made to prove that mod/div operations are often quite inefficient compared to their more basic
//		   counterparts...

#include<ctime>
#include<iostream>
using namespace std;

void DoEfficiencyDebug();

int main()
{
	int ROW(100);
	int iX(0);		//coordinate x
	int iY(0);		//coordinate y
	cout << "Doing 10000000 mod + divide calculations...";
	for (int i = 1; i < 10000000; i++)
	{
		iX = i % ROW;
		iY = i / ROW;
	}
	//clock();
	/*cout << "Doing 10000000 non mod calculations...";
	for (int i = 1; i < 10000000; i++)
	{
		iX++;
		if (iX >= ROW)
		{
			iY++;
			iX = 0;
		}
	}
	*/
	DoEfficiencyDebug();
	
	cin.get();
	return 0;
}


void DoEfficiencyDebug()
{
	cout << "\n\nClock ticks for calculation: " << clock();
	cout << "\n@ " << CLOCKS_PER_SEC << " For Duration: " << clock() / (CLOCKS_PER_SEC / 1000) << " milliseconds";
	return;
}

The div/mod code and the basic iteration both do essentially the same thing (in the program we had to make) which is to plot squares appropriately on a grid. My only issue is that i'm not sure how to reset the clock(), so it has to be run in 2 different instances - one with mod/div commented out, one with it commented in. Does anyone know a reset clock() method?

For anyone who's interested, here's the results from this program (in terms of efficiency):

For 10000000 Calculations:
Mod/Div method : 1492 clock ticks or about 1500 milliseconds
Basic Iteration : 160 clock ticks or about 165 milliseconds

You're all welcome to show your instructors this =) . Although mod/div is occassionally neccessary.

Recommended Answers

All 13 Replies

Why you want to reset system clock? Keep it simpler:

clock_t t0, t1;
t0 = clock();
// do this...
t0 = clock() - t0;
t1 = clock();
// do that...
t1 = clock() - t1;
// Now print t0, t1 and what else...

So your original timing was incorrect (from the PROGRAM START to the current moment).

>I'm trying to prove to my teacher that Div and Mod isn't always the best way to solve things.
I find it humorous that you seem to think "fastest" and "best" are synonymous.

>You're all welcome to show your instructors this =)
Oh, I will indeed. It's a very amusing test, seeing as how an accurate comparison of a feature and it's alternative should produce the same results for both when hoisted out of the timing loop. I'm curious how you think that this:

iX = i % ROW;
iY = i / ROW;

Has identical results to this:

iX++;
if (iX >= ROW)
{
  iY++;
  iX = 0;
}

>I'm trying to prove to my teacher that Div and Mod isn't always the best way to solve things.
I find it humorous that you seem to think "fastest" and "best" are synonymous.

>You're all welcome to show your instructors this =)
Oh, I will indeed. It's a very amusing test, seeing as how an accurate comparison of a feature and it's alternative should produce the same results for both when hoisted out of the timing loop. I'm curious how you think that this:

iX = i % ROW;
iY = i / ROW;

Has identical results to this:

iX++;
if (iX >= ROW)
{
  iY++;
  iX = 0;
}

Well. I'm sorry if a 1300% increase in speed isn't considered better in your opinion, you may be thinking in terms of robustness and end user usability. This is using the same logic as the fastest runner is the best runner in the race, which I hope you can draw a logical connection with. My argument is based entirely on efficiency - the number of calculations required to get the same end result. And sorry, replace iX and iY with iY and iX in the first loop and you will find that they are indeed identical results.

And as for the above solution to my problem, that is indeed the 'fix' i used. But my question is if there are any functions in the ctime library that would reset the clock() variable. I may end up just looking through the microsoft documentation, but I think we all know how painful that can be.

For Narue: This is the latest code for the efficiency test, and you will find the results to be quite identical. I'm sorry for the mixup of the two variables earlier, but I was pretty tired and/or stoned when I originally wrote this.

Note: The efficiency gain in my method decreases to around 300% at lower iterations. But since i've included cout lines to prove the identicality, 100000000 iterations isn't feasable. To fix this take out the couts and increase MAX to 100000000, and row to whatever you want, really.

//Project: Mod_Efficiency
//Author : Kyle Wesley
//Descrip: This was made to prove that mod/div operations are often quite inefficient compared to their more basic
//		   counterparts...

#include<ctime>
#include<iostream>
using namespace std;

int DoEfficiencyDebug(int = 0);
int const MAX(100);
int const ROW(10);

int main()
{
	int iTimeOffset(0);
	int iX(0);		//coordinate x
	int iY(0);		//coordinate y
	double dEff(0);
	cout << "Row Max: " << ROW << endl;
	cout << "Doing " << MAX << " div + mod calculations...";
	for (int i = 1; i < MAX; i++)
	{
		iX = i % ROW;
		iY = i / ROW;
		cout << "\niX: " << iX << " iY: " << iY;
	}
	iX = 0;
	iY = 0;
	iTimeOffset = DoEfficiencyDebug();
	cout << "\n\nDoing " << MAX << " non div + mod calculations...";
	for (int i = 1; i < MAX; i++)
	{
		iX++;
		if (iX >= ROW)
		{
			iY++;
			iX = 0;
		}
		cout << "\niX: " << iX << " iY: " << iY;
	}
	cout << "\niX: " << iX << " iY: " << iY;
	dEff = static_cast<double>(iTimeOffset) / static_cast<double>(DoEfficiencyDebug(iTimeOffset)); 
	cout << "\n\nNon Div Mod Efficiency: " << dEff * 100 << "% more efficient than Div Mod";
	cin.get();
	return 0;
}


int DoEfficiencyDebug(int iOffset)
{
	cout << "\n\nClock ticks for calculation: " << clock() - iOffset;
	cout << "\n@ " << CLOCKS_PER_SEC << " For Duration: " << (clock()-iOffset) / (CLOCKS_PER_SEC / 1000) << " milliseconds";
	return (clock() - iOffset);
}

The win32 api function you want is SetSystemTime()

Thank you very much =).

>I'm sorry if a 1300% increase in speed isn't considered better in your opinion
Certainly not in this case. You failed to describe exactly what you meant by saying "best" (assuming that "best" was execution speed), you failed to compare two equivalent solutions to prove your assertion, and you failed to compare the execution speeds correctly. Therefore your premise was subjective, your test was flawed, and your conclusion was biased.

Show me a legitimate 1300% increase in speed and I'll take you more seriously. :icon_rolleyes:

>This is the latest code for the efficiency test, and you will find the results to be quite identical.
Not when taken out of the timing loop. The timing loop should be only for timing, but your "non div + mod calculations" require it for correct behavior. These two snippets are equivalent without the timing loop:

int iX = i % ROW;
int iY = i / ROW;
int iX = 0;
int iY = 0;

for ( int j = 0; j < i; j++ ) {
  if ( ++iX >= ROW ) {
    ++iY;
    iX = 0;
  }
}

That's what I mean by identical results. If you remove the timing loop and run the code with any value of i, and the result is the same. In your code the result is only the same when run with consecutive values of i, which means your method is dependent on the timing loop while the method you claim to be flawed is not.

>The efficiency gain in my method decreases to around 300% at lower iterations.
The efficiency gain, aside from being biased in that your method being tested is incomplete, is also biased by broken code. You're careful to set the time offset for your method, but for the "slow" method you don't bother and just go with whatever clock() - 0 produces. Your timing code is broken and it's conveniently broken in favor of your method. This is easily proven by swapping the two loop bodies such that your method is tested first. You'll likely find the "1300% increase" to no longer be in your favor.

>I'm sorry if a 1300% increase in speed isn't considered better in your opinion
Certainly not in this case. You failed to describe exactly what you meant by saying "best" (assuming that "best" was execution speed), you failed to compare two equivalent solutions to prove your assertion, and you failed to compare the execution speeds correctly. Therefore your premise was subjective, your test was flawed, and your conclusion was biased.

Show me a legitimate 1300% increase in speed and I'll take you more seriously. :icon_rolleyes:

>This is the latest code for the efficiency test, and you will find the results to be quite identical.
Not when taken out of the timing loop. The timing loop should be only for timing, but your "non div + mod calculations" require it for correct behavior. These two snippets are equivalent without the timing loop:

int iX = i % ROW;
int iY = i / ROW;
int iX = 0;
int iY = 0;

for ( int j = 0; j < i; j++ ) {
  if ( ++iX >= ROW ) {
    ++iY;
    iX = 0;
  }
}

That's what I mean by identical results. If you remove the timing loop and run the code with any value of i, and the result is the same. In your code the result is only the same when run with consecutive values of i, which means your method is dependent on the timing loop while the method you claim to be flawed is not.

>The efficiency gain in my method decreases to around 300% at lower iterations.
The efficiency gain, aside from being biased in that your method being tested is incomplete, is also biased by broken code. You're careful to set the time offset for your method, but for the "slow" method you don't bother and just go with whatever clock() - 0 produces. Your timing code is broken and it's conveniently broken in favor of your method. This is easily proven by swapping the two loop bodies such that your method is tested first. You'll likely find the "1300% increase" to no longer be in your favor.

Ok I swapped them. Your right to a very small degree, in that the initializations and other such shinnanigans do take a very small amount of time. I timed them, actually, and they require about 11 clock ticks (which is entirely insignificant when compared to the thousands required in the end, but still duly noted). But its still about 1000% faster. And I wasn't trying to totally knock off div/mod. If this function were to find the exact location of a given entry in the table then div mod would be the way to go. However, this is merely for building a table, and is a demonstration on how using the supposed 'correct' way can often be surpassed by simpler solutions. The amount of calculations performed at the lowest level by a div/mod is ludicrous for something like this, especially in the scale presented (billions, or even trillions of iterations). Each mod requires a loop in itself, and as MAX increases, the time taken for this loop increases, thus leading to an exponential growth of inefficiency.

While the robustness of the function is hampered by my method (since it does require the timing loop), this particular application of these algorithms definetly does not need the robust capabilities of div/mod. In fact, it's the div/mod calculations that bottleneck the graphical drawer we are using, which is very bad! The div/mod method causes noticable delay between drawings, while mine builds the table (nearly) instantly. I suppose a more in depth explanation could have been due earlier, but I didn't expect my code to face such scrutiny, rather I was searching for an answer to a fairly unrelated problem. But I suppose it's appreciated ;) . Cheers.

>Your right to a very small degree
That's a pretty arrogant statement, all things considered.

>But its still about 1000% faster.
Not on my system. I show a complete reversal of the timings, which means your code is also non-portable. Fancy that.

>I suppose a more in depth explanation could have been due earlier
Too late, you fail.

>but I didn't expect my code to face such scrutiny
You were planning on using that code essentially to prove that your instructor is incompetent. I have trouble seeing how not only you didn't expect close scrutiny by someone, but that you were also so sloppy as to completely fail such scrutiny both in describing the purpose of the code and writing the code itself.

>But I suppose it's appreciated ;)
Bite me. Nothing irritates me more than people dismissing my contributions with a smarmy comment. Don't expect any help from me in the future.

>Your right to a very small degree
That's a pretty arrogant statement, all things considered.

>But its still about 1000% faster.
Not on my system. I show a complete reversal of the timings, which means your code is also non-portable. Fancy that.

>I suppose a more in depth explanation could have been due earlier
Too late, you fail.

>but I didn't expect my code to face such scrutiny
You were planning on using that code essentially to prove that your instructor is incompetent. I have trouble seeing how not only you didn't expect close scrutiny by someone, but that you were also so sloppy as to completely fail such scrutiny both in describing the purpose of the code and writing the code itself.

>But I suppose it's appreciated ;)
Bite me. Nothing irritates me more than people dismissing my contributions with a smarmy comment. Don't expect any help from me in the future.

Well I really don't think you did help me (with my original question). This thread was asking how to clear the clock(), so an explanation of the implementation of my code wasn't necessary - as I feel my post was long enough as it was, and generally expect busy coders to skip longer posts.

Are you running a linux system? Because it ports very well to my fedora core 8 boot. I'll try on ubuntu but expect similar results. Note that the efficiency calculation must also be reversed.

I didn't mean to offend you, I was merely arguing my point, and I felt I addressed most, if not all, of your points. I did not expect such scrutiny in the functionality of my code, since it is obviously not finished yet - seeing as I was stuck at the clock() issue. And I wasn't trying to prove my instructor incompetent. He's a much better coder than I, in fact he wrote most of the libraries we use, a task which I would not be willing to volunteer for (which he did). I'm just trying to show him that the 'official' methods aren't always the 'best' methods per se.

I appologize for the semi-sarcastic end remark, but really you did nothing more than dismiss my work as a failure as opposed to helping (with either the clock() issue or otherwise). At the very least you were as arrogant as I.

Allow me to add some objective info to this slightly overheated thread.
Let's add more realism to these tests: we want to initialize 2D array:

const int ROW = 100;
const int N = ROW*ROW;
int grid[ROW][ROW];

I'm using AMD Athlon 5000+, VC++ 9, release, optimization for speed.
Snippet #1:

for (int i = 1; i < N; i++)
{
    iX = i % ROW;
    iY = i / ROW;
    grid[iY][iX] = i;
}

Timing result: ~180 microseconds.
Snippet #2:

for (int i = 1; i < N; i++)
{
    iX++;
    if (iX >= ROW)
    {
        iY++;
        iX = 0;
    }
    grid[iY][iX] = i;
}

Timing result: ~23 microseconds.
It seems #2 is faster then #1 with factor 8. It's a fast solution. Is it the best solution?
No, it is not.
Snippet #3:

int k = 0;
    for (int i = 0; i < ROW; ++i)
        for (int j = 0; j < ROW; ++j)
            grid[i][j] = k++;

Timing: ~15 microseconds!
All three snippets do the same job. The fastest and simplest solution - absolutely strait-forward, traditional code.

Moral: no moral ;)...

to skatamatic:
It seems you did not read or did not understand my 1st post in the thread.
It was absolutely senseless question: how to clear a tick counter.
No need to clear tick counter: better use it as is.
Or restart the process...

Allow me to add some objective info to this slightly overheated thread.
Let's add more realism to these tests: we want to initialize 2D array:

const int ROW = 100;
const int N = ROW*ROW;
int grid[ROW][ROW];

I'm using AMD Athlon 5000+, VC++ 9, release, optimization for speed.
Snippet #1:

for (int i = 1; i < N; i++)
{
    iX = i % ROW;
    iY = i / ROW;
    grid[iY][iX] = i;
}

Timing result: ~180 microseconds.
Snippet #2:

for (int i = 1; i < N; i++)
{
    iX++;
    if (iX >= ROW)
    {
        iY++;
        iX = 0;
    }
    grid[iY][iX] = i;
}

Timing result: ~23 microseconds.
It seems #2 is faster then #1 with factor 8. It's a fast solution. Is it the best solution?
No, it is not.
Snippet #3:

int k = 0;
    for (int i = 0; i < ROW; ++i)
        for (int j = 0; j < ROW; ++j)
            grid[i][j] = k++;

Timing: ~15 microseconds!
All three snippets do the same job. The fastest and simplest solution - absolutely strait-forward, traditional code.

Moral: no moral ;)...

Hah! Thank you for your constructive input. The only issue I have with your solution is that we aren't allowed to use arrays. It's for the visual construction of a hash table, and the hash table datatype is just a contiguos stream, not pre-parsed into dimensions. The maximum column size is determined by the dimension of the drawer window divided by the size of the rectangles of each entry. So essentially this algorithm is to parse into dimensions, as well as find the coordinates at the same time. (I'd post the code if it wasn't multifiled and so huge...)

I'm sure your algorithm could be modified to accomidate the forementioned fact, and I'll do some experimenting myself. I appreciate your constructive critisism, and that you saw my solution as a valid idea. I want the board to know I'm not an arrogant hot head - I just don't like condescending attitudes.

I understand that resetting the clock is usually not necessary, but for this situation I thought it would help tidy up the code a bit, but I suppose it's really not a big deal. Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.