Java中的int vs float算法效率 [英] int vs float arithmetic efficiency in Java

查看:79
本文介绍了Java中的int vs float算法效率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个使用Dijkstra算法在图形中查找最小路径的应用程序.图中节点和边的权重为float数字,因此该算法对浮点数进行了许多算术运算.如果将所有权重都转换为int,是否可以提高运行时间? Java中的int算术运算比浮点运算要快吗?

我试图编写一个简单的基准来检查该结果,但是我对获得的结果不满意.可能是编译器已经优化了程序的某些部分,所以结果对我来说不太好.


我要解决的问题是在信息检索"字段中.该应用程序应显示以一组关键字构成的查询的答案.

我的数据结构是加权有向图.给定一组叶节点,我必须找到连接这些节点并向用户显示答案的最小树.通过部分基于tf/idf技术的加权函数分配权重.用户不知道我给节点和边缘分配了什么权重,他只想查看与他提出的查询相关的答案.因此,不需要精确的结果,只是根据其权重枚举答案的可能性.只是本机使用加权函数(如我所提到的,它是基于tf/idf的)给出了浮点数权重,所以到目前为止我都使用了浮点数.

我希望这可以为问题添加一些背景.

解决方案

像往常一样,您应该为自己设置一些性能目标,然后对应用程序进行概要分析,看它是否符合要求.

通常您会发现令人惊讶的结果;基本所花费的时间几乎不受基本数字类型的影响,或者您的算法不够理想.

关于编译器优化-它们是优化性能的真实且有效的部分.

如果从理论上说使用类型A的速度比使用类型B的速度快,但是您的编译器可以在实际情况下将类型B优化为更快,那么这就是一个有价值的证据,而不是失望的源头.

I'm writing an application that uses Dijkstra algorithm to find minimal paths in the graph. The weights of the nodes and edges in the graph are float numbers, so the algorithm doing many arithmetics on float numbers. Could I gain a running time improve if I convert all weight to ints? Is int arithmetic operations are faster in Java then float ones?

I tried to write a simple benchmark to check that out, but I'm not satisfied with the results I got. Possibly the compiler has optimized some parts of the program so the results doesn't looks good for me.


EDIT:

The problem I'm trying to solve is in the Information Retrieval field. The application should show answers to a query posed as a set of keywords.

My data structure is a weighted directed graph. Given a set of leaf nodes I have to find a smallest tree that connects these nodes and show the answer to the user. The weights are assigned by a weighting function based partially on the tf/idf technique. The user don't know what weights I assign to the nodes and edges he just wants to see answers relevant to the query he posed. So exact results are not required, just a possibility to enumerate answers according to theirs weights. Just the native use of weighting function (as I mentioned it is based on tf/idf) gives float weights so I used floats so far.

I hope this adds some background to the question.

解决方案

As ever with this sort of thing you should set yourself some performance goals, and then profile the app to see if it meets them.

Often times you may find surprising results; that the time taken is hardly affected by base numerical type at all, or that your algorithm is suboptimal.

And regarding compiler optimisations - they're a real, and valid part of performance optimisation.

If using type A is theoretically faster than using type B, but your compiler can optimise type B to be quicker in a real scenario then thats a valuable piece of evidence, not source for dissapointment.

这篇关于Java中的int vs float算法效率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆