【发布时间】:2020-05-20 07:41:33
【问题描述】:
我的问题是关于经过时间根据点的差异。
为了找到在我的代码中执行时总运行时间的最大部分,我使用了clock 函数。
来源:calculating time elapsed in C++
首先,我把clock函数放在main函数的开头和结尾。
(实际上,有一些变量声明,但我删除它们是为了我的问题的可读性)。然后我想我将能够测量总经过的时间。
int main(){
using clock = std::chrono::system_clock;
using sec = std::chrono::duration<double>;
const auto before = clock::now();
...
std::cin >> a >> b;
lgstCommSubStr findingLCSS(a,b,numberofHT,cardi,SubsA);
const sec duration = clock::now() - before;
std::cout << "It took " << duration.count() << "s in main function" << std::endl;
return 0;
}
其次,我将clock 函数放在findingLCSS 类中。此类用于查找两个字符串之间的最长公共子字符串。它是真正执行我的算法的类。我编写了在其构造函数中查找它的代码。因此,在制作这个类时,它会返回最长的公共子串信息。我认为这个经过的时间将是实际的算法运行时间。
public:
lgstCommSubStr(string a, string b, int numHT, int m, vector <int> ** SA):
strA(a), strB(b), hashTsize(numHT), SubstringsA(SA),
primeNs(numHT), xs(numHT),
A_hashValues(numHT), B_hashValues(numHT),
av(numHT), bv(numHT), cardi(m)
{
using clock = std::chrono::system_clock;
using sec = std::chrono::duration<double>;
const auto before = clock::now();
...
answer ans=binarySearch(a,b, numHT);
std::cout << ans.i << " " << ans.j << " " << ans.length << "\n";
const sec duration = clock::now() - before;
std::cout << "It took " << duration.count() << "s in the class" << std::endl;
}
输出如下。
tool coolbox
1 1 3
It took 0.002992s in inner class
It took 4.13945s in main function
这意味着'tool'和'coolbox'有一个子字符串'ool'
但我很困惑,两次之间有很大的差异。
因为第一次是总时间,第二次是算法运行时间,所以我不得不认为它的差异时间是声明变量的经过时间。
但这看起来很奇怪,因为我认为声明变量的时间很短。
测量经过的时间有误吗?
请给我一个疑难解答的提示。感谢您的阅读!
【问题讨论】:
-
首先欢迎来到 Stack Overflow。请阅读the help pages,获取the SO tour,了解how to ask good questions,以及this question checklist。不要忘记minimal reproducible example 的minimal 部分。
-
那么互联网上肯定有数千个关于各种“最长子串”问题的示例和文档。这里有不少。如果您将此问题的标题复制到您最喜欢的搜索引擎中,那么您会获得多少点击?前十名中有多少是相关的?
-
@Someprogrammerdude 谢谢你的评论。我已经在谷歌搜索过这个,但我没有得到关于我的问题的提示。但我必须按照你说的在 Google 上找到它。
-
std::cin >> a >> b;当然可能需要很长时间,具体取决于输入的来源。 -
@AdrianCornish 是的,我做到了。我在 eclipse 使用“g++ -pipe -std=c++14 -lm -O2 -g3 -Wall -c -fmessage-length=0”编译我的代码。谢谢!
标签: c++ string class elapsedtime