Reputation: 2104
Here's a simple program I wrote to find all the non-decreasing-digit numbers of length <=L whose digits sum upto N. The code works fine, but when I try to clock the run time using clock() from ctime it shows a weird behaviour.
#include<iostream>
#include<vector>
#include<ctime>
using namespace std;
typedef long long int LL;
int Sum(LL S){
int sum=0;
for(;S;S/=10)
sum+=S%10;
return sum;
}
void Generate(LL S, int len, int N, int L, vector<LL> &V){
if(len<L)
for(int i=0;i<=9;++i)
if(i>=S%10)
Generate(S*10+i, len+1, N, L, V);
int sum = Sum(S);
if(sum!=N)
return;
else if(sum == N && len == L){
V.push_back(S);
cout << S << endl; //Line 4
return;
}
}
int main(){
int N,L;
vector<LL> V;
LL S;
cin >> N >> L;
clock_t start=clock(); //Line 1
Generate(S, 0, N, L, V);
//clock_t start=clock(); //Line 2
clock_t end = clock();
for(int i=0;i<V.size();++i)
cout << V[i] << " ";
cout << endl;
cout << "Run time: " << (double)(end-start)/CLOCKS_PER_SEC;
return 0;
}
I record the no. of clock ticks elapsed before calling the "Generate" function at //Line 1 and I do the same afterwards at //Line 2, the difference of which I believe should give me the no. of clock ticks elapsed in generating the required numbers.
But if I do so my function "Generate"'s processing somehow gets affected! It won't output the numbers to stdout(from //Line 4) and even if I pass a vector to store up the generated numbers, it won't store any!
However, if I use clock() at //Line 2 my output on stdout is fine and the referenced vector V gets filled up with the desired result. but clock() on //Line 2 is of no use.
What I fail to understand is How can a call to clock() affect some processing in 'Generate' function, unless of course I've some obscure Bug! or the clock() is not supposed to be used in this kind of recursive setup?
Please help me Debug this.
Upvotes: 0
Views: 626
Reputation: 46963
I get variable S is being used without being initialized in your code. Really you need to initialize it to 0 in the very beginning. From then on the behavior is quite unpredictable - thus from time to time you might get the correct answers, but I doubt it. It does not depend on the calls of clock()
.
Upvotes: 5