Question

I have a program which reads 2 input files. First file contains some random words which are put into an BST and AVL tree. Then the program looks for the words listed in the second read file and says if they exist in the trees, then writes an output file with the information gathered. While doing this the program prints out the time spent for finding a certain item. However the program does not seem to be measuring the time spent.

BST* b = new BST();
AVLTree* t = new AVLTree();

string s;

ifstream in;
in.open(argv[1]);

while(!in.eof())
{
    in >> s;
    b->insert(s);
    t->insert(s);
}

ifstream q;    
q.open(argv[2]);

ofstream out;
out.open(argv[3]);

int bstItem = 0;
int avlItem = 0;
float diff1 = 0;
float diff2 = 0;

clock_t t1, t1e, t2, t2e;

while(!q.eof())
{
    q >> s;

    t1 = clock();
    bstItem = b->findItem(s);
    t1e = clock();

    diff1 = (float)(t1e - t1)/CLOCKS_PER_SEC;        

    t2 = clock();
    avlItem = t->findItem(s);
    t2e = clock();

    diff2 = (float)(t2e - t2)/CLOCKS_PER_SEC;

    if(avlItem == 0 && bstItem == 0)
        cout << "Query " << s << " not found in " << diff1 << " microseconds in BST, " << diff2 << " microseconds in AVL" << endl;

    else
        cout << "Query " << s << " found in " << diff1 << " microseconds in BST, " << diff2 << " microseconds in AVL" << endl;

    out << bstItem << " " << avlItem << " " << s  << "\n"; 
}

The clock() value I get just before entering while and just after finishing it is exactly the same. So it appears as if the program does not even run the while loop at all, so it print 0. I know that this is not the case since it takes around 10 seconds for the program the finish as it should. Also the output file contains correct results, so the possibility of having bad findItem() functions is also not true.

I did a little bit research in Stack Overflow, and saw that many people experience the same problem as me. However none of the answers I read solved it.

Was it helpful?

Solution

I solved my problem using a higher resolution clock, though the clock resolution was not my problem. I used clock_gettime() from time.h. As far as I know higher clock resolutions than clock() is platform dependent and this particular method I used in my code is only available for Linux. I still haven't figured out why I wasn't able to obtain healthy results from clock(), but I suspect platform dependency again.

An important note, the use of clock_gettime() requires you to include POSIX real time extension when compiling the code. So you should do:

g++ a.cpp b.cpp c.cpp -lrt -o myProg

where -lrt is the parameter to include POSIX extensions.

OTHER TIPS

If (t1e - t1) is < CLOCKS_PER_SEC your result will always be 0 because integer division is truncated. Cast CLOCKS_PER_SEC to float.

diff1 = (t1e - t1)/((float)CLOCKS_PER_SEC);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top