Advertisement
jackd5011

FloatBuffer performance testing on arrays

Sep 22nd, 2019
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.52 KB | None | 0 0
  1. import java.nio.ByteBuffer;
  2. import java.nio.FloatBuffer;
  3.  
  4. public class Test {
  5.  
  6.     public static void main(String[] args) {
  7.         float[] data = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
  8.         FloatBuffer buffer = ByteBuffer.allocateDirect(data.length * Float.BYTES).asFloatBuffer();
  9.  
  10.         long start;
  11.  
  12.         // test 1: flip()
  13.         start = preTime("Entire array, flip()");
  14.         {
  15.             buffer.put(data).flip();
  16.         }
  17.         postTime(start, buffer);
  18.         buffer.clear();
  19.  
  20.         // test 2: no flip()
  21.         start = preTime("Entire array, no flip()");
  22.         {
  23.             buffer.put(data);
  24.         }
  25.         postTime(start, buffer);
  26.         buffer.clear();
  27.  
  28.         // test 3: put() with flip()
  29.         start = preTime("Loop through, with put() and flip()");
  30.         {
  31.             for(int i = 0; i < data.length; i++) {
  32.                 buffer.put(data[i]);
  33.             }
  34.             buffer.flip();
  35.         }
  36.         postTime(start, buffer);
  37.         buffer.clear();
  38.  
  39.         // test 3: put() with index, w/o flip()
  40.         start = preTime("Loop through, with put() at index");
  41.         {
  42.             for(int i = 0; i < data.length; i++) {
  43.                 buffer.put(i, data[i]);
  44.             }
  45.         }
  46.         postTime(start, buffer);
  47.         buffer.clear();
  48.  
  49.         // test 5: position(0)
  50.         start = preTime("Entire array, position(0)");
  51.         {
  52.             buffer.put(data).position(0);
  53.         }
  54.         postTime(start, buffer);
  55.         buffer.clear();
  56.     }
  57.  
  58.     private static long preTime(String label) {
  59.         System.out.print(label+ ": ");
  60.         return System.nanoTime();
  61.     }
  62.  
  63.     private static void postTime(long start, FloatBuffer buffer) {
  64.         long ns = System.nanoTime() - start;
  65.         System.out.println("took " + ns + "ns: position = " + buffer.position());
  66.     }
  67.  
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement