本帖最后由 了无尘 于 2012-3-24 19:26 编辑
先贴代码
- public class Demo
- {
-
- public static void main(String[] args)
- {
-
- long curr, taken,curr1, taken1;
- curr = System.currentTimeMillis();
- for(int i = 0; i < 1000000; i++)
- {
- // 根据用户输入打印季节
- // 3 4 5春季 6 7 8夏季 9 10 11秋季 1 2 12冬季
-
- for (int season = 0; season < 14; season++)
- {
- printSeason(season);
- }
- }
- taken = System.currentTimeMillis() - curr;
-
- curr1 = System.currentTimeMillis();
- for(int i = 0; i < 1000000; i++)
- {
- // 根据用户输入打印季节
- // 3 4 5春季 6 7 8夏季 9 10 11秋季 1 2 12冬季
-
- for (int season = 0; season < 14; season++)
- {
- printSeason2(season);
- }
- }
- taken1 = System.currentTimeMillis() - curr1;
-
-
- System.out.println("我的方法耗时为" + taken + "毫秒");
- System.out.println("老师方法耗时为" + taken1 + "毫秒");
- }
-
- static void printSeason(int season)
- {
- if ((season < 13) && (season > 0))
- {
- // 使1 2月份加上12保持月份连续性用以快速区分
- int temp = ((season > 0) && (season < 3)) ? season += 12 : season;
- if (temp > 11)
- {
- System.out.println("" + ((season == 12) ? season : (season % 12)) + "月是冬季");
- }
- else if (temp > 8)
- {
- System.out.println("" + season + "月是秋季");
- }
- else if (temp > 5)
- {
- System.out.println("" + season + "月是夏季");
- }
- else
- {
- System.out.println("" + season + "月是春季");
- }
- }
- else
- {
- System.out.println("" + season + "月不存在");
- }
- }
-
- static void printSeason2(int season)
- {
- if(season > 12 || season < 1)
- System.out.println("" + season + "月不存在");
- else if(season >= 3 && season <= 5)
- System.out.println("" + season + "月是春季");
- else if(season >= 6 && season <= 8)
- System.out.println("" + season + "月是夏季");
- else if(season >= 9 && season <= 11)
- System.out.println("" + season + "月是秋季");
- else
- System.out.println("" + season + "月是冬季");
-
- }
- }
复制代码 我的方法耗时为65692毫秒
老师方法耗时为66062毫秒
这个是运行100万次的
我的方法耗时为6538毫秒
老师方法耗时为6544毫秒
这是10万次的
我的方法耗时为744毫秒
老师方法耗时为665毫秒
这是1万次的
多次测试,时间基本没有变化,不管是1万10万还是100万,1万的肯定就是老师的快,100万的肯定就是我的快。。。俺迷茫了
不过我的这个printSeason方法肯定还能在提高效率的,不过本来就是换种思路和写法,呵呵 |