Weird fluctuation in execution time

Started by
3 comments, last by lride 11 years, 3 months ago

#include <iostream>
int rand(int low, int high){return rand () % (high - low + 1) + low;}

const int nDATA=1;

std::array<int, 100> data;
int count[10];

	
void task0(){++count[0]; std::cout<<"A\n"<<std::endl;}
void task1(){++count[1]; std::cout<<"B\n"<<std::endl;}
void task2(){++count[2]; std::cout<<"C\n"<<std::endl;}
void task3(){++count[3]; std::cout<<"D\n"<<std::endl;}
void task4(){++count[4]; std::cout<<"E\n"<<std::endl;}
void task5(){++count[5]; std::cout<<"F\n"<<std::endl;}
void task6(){++count[6]; std::cout<<"G\n"<<std::endl;}
void task7(){++count[7]; std::cout<<"H\n"<<std::endl;}
void task8(){++count[8]; std::cout<<"I\n"<<std::endl;}
void task9(){++count[9]; std::cout<<"J\n"<<std::endl;}

int main()
{
	for(int i=0; i<100; ++i)
		data[i]=rand(0, nDATA-1);	//Generate Data

	for(int i=0; i<10; ++i)		//initialize count 
		count[i]=0;

	Timer timer;
	for(int n=1; n<=500; ++n)
	{
		for(int i:data)
		{
			switch(i)
			{
			case 0:task0();break;
			case 1:task1();break;
			case 2:task2();break;
			case 3:task3();break;
			case 4:task4();break;
			case 5:task5();break;
			case 6:task6();break;
			case 7:task7();break;
			case 8:task8();break;
			case 9:task9();break;
			}
		}
	}




	std::cout<<timer.getElapsedTime()<<"\n";
	std::cin.get();

}

sometime above code finished in 7 seconds, but sometimes 25 seconds regardless what nDATA is set to.

Why..??

An invisible text.
Advertisement

It doesn't happen with g++4.6.3 on Linux. What compiler are you using and with what options?

Windows, VS2012, /Ox(full op) in release

@Alvaro: does the execution become slower as nDATA is set to larger number?

An invisible text.

No, it seems to be about constant up to nDATA=10 and then it gets faster because there is less stuff to print.

One comment about your code: The C++ way of expressing a range is by including the beginning and excluding the end. If you had followed that convention in your function `rand', you wouldn't be subtracting 1 from nDATA when you call it and adding it back in inside the function. In other words, things are simpler and you are less likely to have off-by-one errors if you adopt this convention. I highly recommend it.

Yes, I should definately follow that convention from now. Thanks

An invisible text.

This topic is closed to new replies.

Advertisement