java获取系统时间并打印计算100万次字符串相加耗时


package com.javabase.p1;

import java.text.SimpleDateFormat;


public class TestTime {

	/**
	 * 获取系统时间 并格式化打印
	 * @param str 字符串
	 */
	public static void str_add_test_StringBuilder(String str) {
		final int cont = 1000000;
		// 获取系统时间
		long startTime = System.currentTimeMillis();

		// 年月日 时分秒 毫秒
		// yyyy-MM-dd HH:mm:ss
		SimpleDateFormat sDatef = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
		// 格式化输出字符串时间
		String s = sDatef.format(startTime);
		System.out.println(s); // 打印当前时间

		
		StringBuilder sBud = new StringBuilder();
		//100万次字符串相加
		for (int i = 0; i < cont; i++) {
			sBud.append(str);
		}

		long endTime = System.currentTimeMillis();
		System.out.println("100万次字符串相加 StringBuilder CPU耗时:   " + (endTime - startTime)+ "毫秒");
	}

	public static void str_add_test_StringBuffer(String str){
		final int cont = 1000000;
		// 获取系统时间
		long startTime = System.currentTimeMillis();

		// 年月日 时分秒 毫秒
		// yyyy-MM-dd HH:mm:ss
		SimpleDateFormat sDatef = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss mmm");
		// 格式化输出字符串时间
		String s = sDatef.format(startTime);
		System.out.println(s); // 打印当前时间

		
		StringBuffer sBuf = new StringBuffer();
		//100万次字符串相加
		for (int i = 0; i < cont; i++) {
			sBuf.append(str);
		}

		long endTime = System.currentTimeMillis();
		System.out.println("100万次字符串相加 StringBuffer CPU耗时:   " + (endTime - startTime) + "毫秒");
	}

	public static void main(String[] args) {
		
		String str = "我想去海南吃鲍鱼和龙虾";
		str_add_test_StringBuffer(str);
		
		//100万次字符串相加运算 stringbuilder速度更快
		str_add_test_StringBuilder(str);

	

	}

}






猜你喜欢

转载自blog.csdn.net/qq_43314793/article/details/90139282
今日推荐