分析用 C 编写的函数的时间复杂度
我正在用 C 实现最长公共子序列问题。我希望比较解决方案的递归版本和动态编程版本的执行时间。如何找到在两个版本中针对各种输入运行 LCS 功能所需的时间?我还可以使用 SciPy 将这些值绘制在图表上并推断时间复杂度吗?
预先感谢,
剃刀
I was implementing Longest Common Subsequence problem in C. I wish to compare the time taken for execution of recursive version of the solution and dynamic programming version. How can I find the time taken for running the LCS function in both versions for various inputs? Also can I use SciPy to plot these values on a graph and infer the time complexity?
Thanks in advance,
Razor
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于问题的第二部分:简短的答案是肯定的,可以。您需要以易于从 Python 解析的格式获取两个数据集(每个解决方案一个)。类似于:
每行xyz
,其中 x 是序列长度,y 是动态求解所需的时间,z 是递归求解所需的时间
然后,在 Python 中:
For the second part of your question: the short answer is yes, you can. You need to get the two data sets (one for each solution) in a format that is convenient to parse with from Python. Something like:
x y z
on each line, where x is the sequence length, y is the time taken by the dynamic solution, z is the time taken by the recursive solution
Then, in Python:
计算处理器时间的最简单方法是使用
time.h
中的clock()
函数:由于您只是比较不同的实现,因此不需要转换时钟转换为实时单位。
The simplest way to account processor time is to use the
clock()
function fromtime.h
:Since you are simply comparing different implementations, you don't need to convert the clocks into real time units.
有多种方法可以做到这一点。更简单的方法之一是找到一些可以执行高分辨率(微秒或更小)间隔计时的代码。将对开始计时器和停止计时器函数的调用包装在对 LCS 函数的调用周围,然后打印生成的经过时间:
对于 lcs_dynamic() 函数来说也是如此。
如果单次迭代的时间太短,则对函数进行循环。我通常将计时代码放入一个函数中,然后调用几次以获得一致的结果。
我可以向您指出所示的包装。
是的,您可以小心地将结果输入 SciPy 等绘图包中。显然,您必须参数化测试大小,并在每种大小下对代码进行多次计时。
There are various ways to do it. One of the simpler is to find some code that does high resolution (microsecond or smaller) timing of intervals. Wrap calls to the start-timer and stop-timer functions around the call to the LCS function, then print the resulting elapsed time:
Similarly for the
lcs_dynamic()
function.If the time for a single iteration is too small, then wrap a loop around the function. I usually put the timing code into a function, and then call that a few times to get consistent results.
I can point you to the package illustrated.
Yes, you could feed the results, with care, into a graphing package such as SciPy. Clearly, you'd have to parameterize the test size, and time the code several times at each size.