qileilove

          blog已經轉移至github,大家請訪問 http://qaseven.github.io/

          并發性能測試程序編寫

           一般要測試軟件或者庫的性能,需要在多線程條件下進行。本文提供一種編寫多線程性能測試的模板,方便大家參考和使用。
            本文以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);
          return result;
          }
          }
          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 cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            現在我們要對比每次加密和解密都執行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 沒必要非點單寫成一個類,這里是為了讓代碼更容易懂。

          posted on 2014-06-10 09:46 順其自然EVO 閱讀(479) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          <2014年6月>
          25262728293031
          1234567
          891011121314
          15161718192021
          22232425262728
          293012345

          導航

          統計

          常用鏈接

          留言簿(55)

          隨筆分類

          隨筆檔案

          文章分類

          文章檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 尚义县| 棋牌| 邻水| 宣化县| 治县。| 临清市| 清河县| 兴业县| 通州区| 峡江县| 双牌县| 榕江县| 抚松县| 卢湾区| 鹤岗市| 旅游| 商洛市| 贞丰县| 汉寿县| 亳州市| 浮梁县| 阜平县| 马关县| 泗水县| 枣强县| 江川县| 凤城市| 清涧县| 六安市| 连平县| 太保市| 安陆市| 遵义县| 武安市| 三门峡市| 轮台县| 凤台县| 来安县| 绍兴市| 驻马店市| 齐河县|