简体   繁体   English

测量Java算法的性能

[英]Measuring Performance of a java algorithm

How can i measure the performance of my java algorithm effectively ? 我怎样才能有效地测量Java算法的性能? is there any accurate way of doing it? 有什么准确的方法吗?

i read other questions of same kind but not satisfied. 我读过其他同类问题,但不满意。 any help would be appreciated. 任何帮助,将不胜感激。

long reference=System.nanoTime();
your_funct();
long finishm=System.nanoTime();

System.out.println( ( (double)(finishm-reference) )/1000000000.0);  //in seconds

Has a meaningful level of ~0.003 seconds in my machine. 在我的机器中具有〜0.003秒的有意义的水平。 I mean, you measure in nano-seconds but smallest step is around 3000000 nanoseconds in my machine. 我的意思是,您以纳秒为单位进行测量,但是在我的机器中,最小步长约为3000000纳秒。

You ask for performance which indicates some sort of timing. 您要求表现出某种时机的性能。 But then what would you compare against? 但是,您将与之作比较吗?

A general way of measuring an algorithm is using Big O, which takes a simplified mathematical approach. 测量算法的一般方法是使用Big O,它采用简化的数学方法。

To explain this at a very basic level a simple linear search of a list of integers has a linear (n) worst case big o. 为了从基本的角度解释这一点,对整数列表的简单线性搜索具有一个线性(n)最坏情况下的大o。 Eg: for(int i = 0; i < sizeofarray; ++i) if(array[i] == to_find) return i; 例如:for(int i = 0; i <sizeofarray; ++ i)if(array [i] == to_find)返回i;

At the worst case this would take i iterations (often number is referred to as n in big o) - so we call it n or linear complexity algorithm. 在最坏的情况下,这将需要进行i次迭代(通常在big o中将数字称为n)-因此我们将其称为n或线性复杂度算法。

Something like a bubblesort algorithm is a loop within a loop so we have n * n complexity = n^2 or quadratic complexity. 像冒泡排序算法之类的东西是一个循环中的一个循环,因此我们具有n * n复杂度= n ^ 2或二次复杂度。

Comparing like with like, if we just consider sorting, quicksort is more efficient than quadratic complexity (it is n log n complexity) so you can consider quicksort being 'better' than bubblesort. 与like比较,如果我们仅考虑排序,则快速排序比二次复杂度(n log n复杂度)更有效,因此您可以认为快速排序比冒泡排序“更好”。

So when evaluating your algorithm think about it in terms of n. 因此,在评估算法时,请考虑n。 Is there a loop? 有循环吗? how many? 多少? The fewer the better. 越少越好。 No loops even better - constant big o. 没有循环会更好-持续不断的大o。

If can make it practical or theoretical. 如果可以使其实用或理论。 If practical then put a timer before the algorithm starts and stop it when it ends. 如果可行,则在算法开始之前放置一个计时器,并在算法结束时将其停止。 If theoretical then use Big O notation (isn't that hard) and you'll get an estimate of its time or space complexity. 如果从理论上讲,则使用Big O表示法 (并不难),您将获得其时间或空间复杂度的估计值。

You can use some profilers. 您可以使用一些分析器。 Many IDEs (such as Netbeans) have one. 许多IDE(例如Netbeans)都有一个。

最好的方法仍然是java.lang.System.currentTimeMillis(),因为无论您使用的是哪种IDE,它都可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM