为什么我的函数计时器一直保持为零作为输出?

时间:2011-12-05 05:25:21

标签: c++ hash runtime clock

我的时间不断变为零。我需要计算通过哈希表搜索的总时间和平均时间。有人可以告诉我我做错了什么吗?

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();
}

3 个答案:

答案 0 :(得分:4)

你正在进行整数除法:

(double)(time/CLOCKS_PER_SEC)*1000;

你想要在()内投射:

((double)time/CLOCKS_PER_SEC)*1000;

此外,我不确定你为什么要将它分配回time,因为那是一个整数变量。如果你想要它在几毫秒内,你可能想要明确它:

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

编辑:

我最初忽略了这一点(因为水平滚动),但你也在打印行的末尾有整数除法:

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

您可能也希望将其转换为double

答案 1 :(得分:3)

Mysticial回答了您的问题,但我建议您不要使用clock()。如果你的编译器支持C ++ 11,那么有一个更好的选择#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";

}

答案 2 :(得分:0)

你的问题与this one非常相似,我的答案在这里适用(不计算一项操作,但其中有一百万次)。