我有一个读取 2 个输入文件的程序。第一个文件包含一些随机词,这些词被放入 BST 和 AVL 树中。然后程序查找第二个读取文件中列出的单词并判断它们是否存在于树中,然后将收集到的信息写入输出文件。在执行此操作时,程序会打印出查找某个项目所花费的时间。然而,该程序似乎并未衡量花费的时间。
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";
}
我在进入之前和完成之后获得的 clock() 值完全相同。所以它看起来好像程序根本没有运行 while 循环,所以它打印 0。我知道这不是这种情况,因为程序完成它应该花费大约 10 秒。此外,输出文件包含正确的结果,因此 findItem() 函数错误的可能性也不成立。
我在 Stack Overflow 上做了一点研究,发现很多人遇到了和我一样的问题。然而,我阅读的所有答案都没有解决它。
最佳答案
我使用更高分辨率的时钟解决了我的问题,尽管时钟分辨率不是我的问题。我使用了 time.h 中的 clock_gettime()。据我所知,比 clock() 更高的时钟分辨率取决于平台,我在代码中使用的这种特殊方法仅适用于 Linux。我仍然没有弄清楚为什么我无法从 clock() 获得健康的结果,但我再次怀疑平台依赖性。
重要说明,使用 clock_gettime() 要求您在编译代码时包含 POSIX 实时扩展。 所以你应该这样做:
g++ a.cpp b.cpp c.cpp -lrt -o myProg
其中 -lrt 是包含 POSIX 扩展的参数。
关于C++ 时钟错误地测量时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16132574/