一般要測試軟體或者庫的性能,需要在多線程條件下進行。本文提供一種編寫多線程性能測試的模闆,友善大家參考和使用。
本文以AES加密和解密為例,并指出Cipher的擷取在程式中的不同位置會對程式性能造成的影響。
程式代碼如下:
package com.lazycat.secure.aes;
import java.nio.charset.Charset;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
public class AESCoder {
public static int count = 1000000;
public static CountDownLatch latch =new CountDownLatch(count);
public static void main(String[] args)throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(200);
final byte[] payload = "{\"msg\":{\"content\":{\"text\":\"JJH\",\"tplId\":0},\"from\":{\"name\":\"10000213\",\"id\":1,\"type\":0},\"to\":{\"name\":\"10095812\",\"id\":10000213,\"type\":0},\"time\":0,\"txid\":0,\"subtype\":1},\"type\":\"chat\"}".getBytes(Charset.forName("utf-8"));
final String secureKey ="BBmFdTFVgAjgHNwRkWWRcOFFiBzAANFU9DmMAP1JpBmc.";
long start = System.currentTimeMillis();
for(int i = 0 ; i <count ; i++){
pool.execute(new Runnable() {
public void run() {
AESCoder coder = new AESCoder();
byte[] enret =null;
try {
enret = coder.encrypt(payload,secureKey);
byte[] deret = coder.decrypt(enret, secureKey);
System.out.println(new String(deret,"utf-8"));
} catch (Exception e) {
e.printStackTrace();
}
latch.countDown();
}
});
}
latch.await();
System.out.println(System.currentTimeMillis() - start);
pool.shutdown();
}
private byte[] encrypt(byte[] payload,String securekey)throws Exception{
byte[] enCodeFormat = securekey.substring(0, 16).getBytes();
SecretKeySpec key = newSecretKeySpec(enCodeFormat,"AES");
Cipher cipher = CliperInstance.getInstance();//建立密碼器
//Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);//初始化
byte[] result = cipher.doFinal(payload);
return result;
public byte[] decrypt(byte[] buffer,StringsecureKey)throws Exception{
byte[] enCodeFormat = secureKey.substring(0,16).getBytes();
SecretKeySpec key = newSecretKeySpec(enCodeFormat,"AES");
//Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//建立密碼器
Cipher cipher = CliperInstance.getInstance();
cipher.init(Cipher.DECRYPT_MODE, key);//初始化
byte[] result = cipher.doFinal(buffer);
}
class CliperInstance {
private static ThreadLocal<Cipher> cipherTL =new ThreadLocal<Cipher>(){
@Override
protected Cipher initialValue() {
try {
return Cipher.getInstance("AES/ECB/PKCS5Padding");
}catch(Exception e){
return null;
}
};
public static CiphergetInstance() throws NoSuchAlgorithmException, NoSuchPaddingException{
returncipherTL.get();
上述代碼中有兩個方法,分别是encrypt和decryption,分别表示加密和解密。
為了簡單,可以被多個線程共用,是以将CountDownLatch定義為static。
在main函數中,建立了固定大小的線程池(200個線程,這個可以根據需要進行調整)和用于加密的payload和秘鑰secureKey。Start用于記錄開始時間,通過最後的System.currentTimeMillis()-start即可獲得程式的運作時間。在for循環中,并發執行了count(10W)次payload的加密和解密,每個線程在執行完一個任務後會調用latch.countDown(),而主程式在循環後使用latch.await(),等待所有線程執行結束後,統計執行時間,輸出消耗時間,最後關閉線程池。
一般在做對比或者尋找瓶頸時,才會使用性能測試,下面給出一個性能對比的例子。
在前面的代碼中,無論是encrypt,還是decrypt,都有如下内容:
Cipher cipher = CliperInstance.getInstance();//建立密碼器
現在我們要對比每次加密和解密都執行Cipher.getInstance方法和對每一個線程自己都維護一個Cipher執行個體的性能差别。(我們都知道,Ciper.getInstance的調用時很耗時的)。
使用Ciphercipher = CliperInstance.getInstance(); 時,執行100W次加密和解密,大約使用11.2s,而使用Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); 大約需要39.6s,是以在進行加密、解密、簽名等算法時,最好每個線程維護一個加密、解密或者簽名的執行個體(這些執行個體是不能再多線程間共享的,如上例所示,調用init和doFinal必須在一個線程内完成,如果全局共享同一個執行個體,A調用init,B也調用了init,當A調用doFinal時,此時執行個體内的資料已經不是A的了,會出現異常)。
順便說一下,如果要求每個線程有自己的執行個體的情況下(如上面的加密和解密等),那麼就可以使用ThreadLocal,在使用ThreadLocal時,重寫内部的initialValue 方法,每次調用ThreadLocal的get方法時,ThreadLocal執行個體先到自己的Map中尋找有沒有目前線程對應的Instance,如果存在,将Instance傳回,如果不存在,調用initialValue去建立一個Instance,并将新Instance放到Map中後,傳回。詳情參看JDK文檔。
需要注意的是,CliperInstance 沒必要非點單寫成一個類,這裡是為了讓代碼更容易懂。