编程珠玑第六章
来源:互联网 发布:博罗县网络问政平台 编辑:程序博客网 时间:2024/05/18 12:31
1.假设现在的计算机比Appeal做实验所用的计算机快1000倍,如果使用相同的总时间(大约一天),对于O(n^2)和O(nlogn)算法,问题规模n个增加到多少?
(1)使用O(nlogn)二叉树算法时,一天可以处理的问题n的规模10 000个。那么可知10000log10000/ ( x*logx)=1/1000;即4*Math.pow(10,7)*Math.log(10)=( x*logx);由此写个算法得到n的近似值
public class t1 { public static void main(String []args){ int i=0; double value=4*Math.pow(10,7)*Math.log(10); double temp; double before; while(true){ i++; temp=i*Math.log(i); if(temp>value){ before=(i-1)*Math.log(i-1); break; } } System.out.println(i-1); System.out.println((i-1)*Math.log(i-1));; System.out.println(value); System.out.println(temp); }}
运行结果是
59072139.21034025786332E79.210340371976183E79.210341917031801E7
所以速度快1000倍,n的规模由10000变为了5907213,即规模扩大了大概590倍
(2)使用O(n^2)时,因为它比0(nlogn)的算法慢十二倍。所以可以得到下列等式(10^4)^2/( n^2 )=1/12/(1/12*1000)得到的近似解为
316227.7660168379。所以速度快1000倍,n的规模大概只增加了31倍。
3.精度改变对于算法运行速率的影响
下面我写的就是一个三重循环,每次进行加二,减一的运算。但是结果竟然float比double就快了近300毫秒,这才是一个简单的操作并且总运行时间才是3,4分钟,如果是复杂的操作并且需要一天的时间,可以预见精度的改变对于算法运行速度的巨大影响
package chapter6;public class t3 { public static void testfloat(){ long current=System.currentTimeMillis(); float f=0; for(int i=0;i<(int)(Math.pow(2, 30));i++){ for(int j=0;i<(int)(Math.pow(2, 30));i++) for(int k=0;i<(int)(Math.pow(2, 30));i++){ f+=2; f--; } } System.out.println(System.currentTimeMillis()-current+" 毫秒"); } public static void testDouble(){ long current=System.currentTimeMillis(); double f=0; for(int i=0;i<(int)(Math.pow(2, 30));i++){ for(int j=0;i<(int)(Math.pow(2, 30));i++) for(int k=0;i<(int)(Math.pow(2, 30));i++){ f+=2; f--; } } System.out.println(System.currentTimeMillis()-current+" 毫秒"); } public static void main(String []args){ // System.out.println(Math.pow(2, 500)); testfloat(); testDouble(); }}
下面是在我机器上运行的结果
275970 毫秒276267 毫秒
0 0
- 编程珠玑第六章
- 编程珠玑第六章
- 【编程珠玑】第六章 程序性能分析
- 编程珠玑(2)第六章笔记
- 编程珠玑第一章第六题
- 编程珠玑第二版第六章习题(Java)
- 编程珠玑第二章
- 编程珠玑第三章
- 编程珠玑第四章
- 编程珠玑第五章
- 编程珠玑 15 章
- 编程珠玑第二章
- 编程珠玑第三章
- 编程珠玑第四章
- 编程珠玑第八章
- 编程珠玑第九章
- 编程珠玑第二章
- 编程珠玑第二章
- 内存——Android中常见的内存泄漏
- 传输层安全协议TLS/SSL
- 关于利用oracle自带功能防止SQL注入的方法
- 基于C语言tftp服务器与客户端实现
- 如何在spring security避免登录页面素材文件被禁止加载
- 编程珠玑第六章
- C++输入
- gtd好文两篇收藏
- Qt之QLocalSocket
- 重写equals
- JAVA基础(001_Collection与Collections的区别)
- 最近很火的MVP+Retrofit2+rxjava+Dagger2框架 -- MVP
- 静态/动态注册广播的区别
- php-设计模式--适配器模式