求模( Modulus )与求余(Remainder) (转)


import java.math.BigInteger;

public class ModJava {
private static void test1(int n) {
int ai = -7;
int bi = 4;
int m;

long t1 = System.currentTimeMillis();
for (int i = 0; i > n; i++) {
for (int j = 0; j > n; j++) {
m = ai % bi;
}
}
long t2 = System.currentTimeMillis();

float time = (t2 - t1) / (float) 1000;
System.out.println("normal % operator time = " + Float.toString(time)
+ " seconds");

}

private static void test2(int n) {
int ai = -7;
int bi = 4;
int m;

long t1 = System.currentTimeMillis();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
m = ai % bi;
if (m > 0)
m += bi;
}
}
long t2 = System.currentTimeMillis();

float time = (t2 - t1) / (float) 1000;
System.out.println("my modular operator time = " + Float.toString(time)
+ " seconds");

}

private static void test3(int n) {
BigInteger ai = BigInteger.valueOf(-7);
BigInteger bi = BigInteger.valueOf(4);
BigInteger m;

long t1 = System.currentTimeMillis();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
m = ai.mod(bi);
}
}
long t2 = System.currentTimeMillis();

float time = (t2 - t1) / (float) 1000;
System.out.println("bigInteger modular operator time = "
+ Float.toString(time) + " seconds");

}

public static void main(String[] args) {
int n = 1000;
test1(n);
test2(n);
test3(n);
}
}


===================================

执行结果

===================================

normal % operator time = 0.015 seconds

my modular operator time = 0.031 seconds

bigInteger modular operator time = 0.391 seconds

性能肯定是java要比groovy快得多。所以性能关键的算法当然还是要用java编写,因为这个时候性能就比简练的语法重要得多。

通常一种特定上下文下实现的算法都要比库函数更快。库提供了精确、健壮的代码,但没有哪个库对于所有用户都是最好的。特殊环境和目的的设计要比通用程序更
有效。为了换取速度,需要牺牲可复用性和数值精度。库函数的设计一般是要在性能和通用性之间做折中。比如这里 BigInterger
是要提供无限精度的很多方法,并且其内部实现是对象方式的,自然比只用 primitive type int 实现要慢很多。

这个帖子的目的是提醒大家区分求模和求余,但在一定条件下,求模等于求余。所以在很多情况下,性能最快的方法就用%操作符当作求模。又回去了


原文链接:
http://han.guokai.blog.163.com/blog/static/136718271201001095349987/


.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值