1

I keep getting zero as my time. I need to calculate the total time and the average time for searching though the hash table. Can someone please tell me what i am doing wrong?

void HashTable_chaining::SearchChainingHT(vector<string> QueryArray)
{
    clock_t start, stop, time = 0;
    int i = 0;
    while(i != QueryArray.size())
    {
        start = clock();
        find(QueryArray[i]);
        stop = clock();
        time += stop - start;
        i++;
    }
    time = (double)(time/CLOCKS_PER_SEC)*1000;
    cout << "\nThe total time for Search Chaining was " << time << "\nThe average time was " << time/QueryArray.size();
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
user977154
  • 1,045
  • 4
  • 19
  • 39
  • Since `time` is a standard function declared in `` (or ``), I wouldn't give a local variable the same name. It probably doesn't matter in this case, but it could be confusing to a reader. – Keith Thompson Dec 05 '11 at 06:31

3 Answers3

4

You're doing integer division:

(double)(time/CLOCKS_PER_SEC)*1000;

you want the cast inside the () instead:

((double)time/CLOCKS_PER_SEC)*1000;

Furthermore, I'm not sure why you are assigning it back to time since that's an integer variable. If you wanted it in milliseconds, you might want to make it explicit:

cout << "\nThe total time for Search Chaining was " << time << "  (milliseconds)" << ...

EDIT :

I overlooked this initially (because of the horizontal scrolling), but you also have integer division here at the end of the printing line:

.. << "\nThe average time was " << time/QueryArray.size();

You may want to cast that one to double as well.

Mysticial
  • 464,885
  • 45
  • 335
  • 332
3

Mysticial answers your question, but I'd like to recommend not using clock() at all. If you're compiler supports C++11 there's a better option, #include <chrono>.

#include <chrono>

void HashTable_chaining::SearchChainingHT(vector<string> QueryArray)
{

    typedef std::chrono::steady_clock Clock;

    Clock::duration total_time = Clock::duration::zero();
    int i = 0;
    while(i != QueryArray.size())
    {
        Clock::time_point start = Clock::now();
        find(QueryArray[i]);
        total_time += Clock::now() - start;
        i++;
    }
    typedef std::chrono::duration<double,std::micro> microseconds;
    typedef std::chrono::duration<double,std::nano> nanoseconds;
    cout << "\nThe total time for Search Chaining was " << microseconds(total_time).count() << " microseconds.\n";
    cout << "The average time was " << nanoseconds(total_time/(double)QueryArray.size()).count() << " nanoseconds.\n";

}
bames53
  • 86,085
  • 15
  • 179
  • 244
0

Your question is very similar to this one, and my answer there applies here (don't count one operation, but a million of them).

Community
  • 1
  • 1
Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547