/* (non-Javadoc)
  * @see chu.engine.Game#loop()
  */
 @Override
 public void loop() {
   while (!Display.isCloseRequested()) {
     final long time = System.nanoTime();
     glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
     glClearDepth(1.0f);
     getInput();
     final ArrayList<Message> messages = new ArrayList<>();
     if (client != null) {
       synchronized (client.messagesLock) {
         messages.addAll(client.messages);
         for (Message m : messages) client.messages.remove(m);
       }
     }
     SoundStore.get().poll(0);
     glPushMatrix();
     // Global resolution scale
     //			Renderer.scale(scaleX, scaleY);
     currentStage.beginStep(messages);
     currentStage.onStep();
     currentStage.processAddStack();
     currentStage.processRemoveStack();
     currentStage.render();
     //				FEResources.getBitmapFont("stat_numbers").render(
     //						(int)(1.0f/getDeltaSeconds())+"", 440f, 0f, 0f);
     currentStage.endStep();
     glPopMatrix();
     Display.update();
     timeDelta = System.nanoTime() - time;
   }
   AL.destroy();
   Display.destroy();
   if (client != null && client.isOpen()) client.quit();
 }
Beispiel #2
0
  private static void runJaversionTree(Integer[] data) {
    out.println("Javersion PersistentTreeMap");
    @SuppressWarnings("unchecked")
    PersistentTreeMap<Integer, Integer> jmap = PersistentTreeMap.EMPTY;
    // warmup
    for (Integer v : data) {
      jmap = jmap.assoc(v, v);
    }
    jmap = null;
    //        System.gc();

    long begin = System.nanoTime();
    for (int i = 1; i <= data.length; i++) {
      start();
      jmap = PersistentTreeMap.EMPTY;
      for (int j = 0; j < i; j++) {
        jmap = jmap.assoc(data[j], data[j]);
      }
      for (int j = 0; j < i; j++) {
        jmap = jmap.dissoc(data[j]);
      }
      out.println(end());
    }
    out.println(String.format("\nJaversion total time: %s", System.nanoTime() - begin));
  }
Beispiel #3
0
  private static void runClojure(Integer[] data) {
    out.println("Clojure PersistentHashMap");
    clojure.lang.PersistentHashMap cmap = clojure.lang.PersistentHashMap.EMPTY;

    // warmup
    for (Integer v : data) {
      cmap = (clojure.lang.PersistentHashMap) cmap.assoc(v, v);
    }
    cmap = null;
    System.gc();

    long begin = System.nanoTime();
    for (int i = 1; i <= data.length; i++) {
      start();
      cmap = clojure.lang.PersistentHashMap.EMPTY;
      for (int j = 0; j < i; j++) {
        cmap = (clojure.lang.PersistentHashMap) cmap.assoc(data[j], data[j]);
      }
      for (int j = 0; j < i; j++) {
        cmap = (clojure.lang.PersistentHashMap) cmap.without(data[j]);
      }
      out.println(end());
    }
    out.println(String.format("\n%s", System.nanoTime() - begin));
  }
Beispiel #4
0
  /**
   * Returns object of class ‘"proc_time"’ which is a numeric vector of length 5, containing the
   * user, system, and total elapsed times for the currently running R process, and the cumulative
   * sum of user and system times of any child processes spawned by it on which it has waited.
   *
   * <p>_The ‘user time’ is the CPU time charged for the execution of user instructions of the
   * calling process. The ‘system time’ is the CPU time charged for execution by the system on
   * behalf of the calling process._
   */
  @Builtin("proc.time")
  public static DoubleVector procTime() {

    DoubleArrayVector.Builder result = new DoubleArrayVector.Builder();
    StringVector.Builder names = new StringVector.Builder();

    long totalCPUTime;
    long userCPUTime;
    long elapsedTime;

    // There doesn't seem to be any platform-independent way of accessing
    // CPU use for the whole JVM process, so we'll have to make do
    // with the timings for the thread we're running on.
    //
    // Additionally, the MX Beans may not be available in all environments,
    // so we need to fallback to app
    try {
      ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
      totalCPUTime = threadMXBean.getCurrentThreadCpuTime();
      userCPUTime = threadMXBean.getCurrentThreadUserTime();

      RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
      elapsedTime = runtimeMXBean.getUptime();
    } catch (Error e) {
      // ThreadMXBean is not available in all environments
      // Specifically, AppEngine will throw variously SecurityErrors or
      // ClassNotFoundErrors if we try to access these classes
      userCPUTime = totalCPUTime = java.lang.System.nanoTime();
      elapsedTime = new Date().getTime();
    }

    // user.self
    names.add("user.self");
    result.add(userCPUTime / NANOSECONDS_PER_SECOND);

    // sys.self
    names.add("sys.self");
    result.add((totalCPUTime - userCPUTime) / NANOSECONDS_PER_SECOND);

    // elapsed
    // (wall clock time)
    names.add("elapsed");
    result.add(elapsedTime);

    // AFAIK, we don't have any platform independent way of accessing
    // this info.

    // user.child
    names.add("user.child");
    result.add(0);

    // sys.child
    names.add("sys.child");
    result.add(0);

    result.setAttribute(Symbols.NAMES, names.build());
    result.setAttribute(Symbols.CLASS, StringVector.valueOf("proc_time"));
    return result.build();
  }
Beispiel #5
0
  /**
   * Blocks the current Thread (<code>Thread.currentThread()</code>) until the receiver finishes its
   * execution and dies or the specified timeout expires, whatever happens first.
   *
   * @param millis The maximum time to wait (in milliseconds).
   * @param nanos Extra nanosecond precision
   * @throws InterruptedException if <code>interrupt()</code> was called for the receiver while it
   *     was in the <code>join()</code> call
   * @see Object#notifyAll
   * @see java.lang.ThreadDeath
   */
  public final void join(long millis, int nanos) throws InterruptedException {
    if (millis < 0 || nanos < 0 || nanos >= NANOS_PER_MILLI) {
      throw new IllegalArgumentException("bad timeout: millis=" + millis + ",nanos=" + nanos);
    }

    // avoid overflow: if total > 292,277 years, just wait forever
    boolean overflow = millis >= (Long.MAX_VALUE - nanos) / NANOS_PER_MILLI;
    boolean forever = (millis | nanos) == 0;
    if (forever | overflow) {
      join();
      return;
    }

    VMThread t = vmThread;
    if (t == null) {
      return;
    }

    synchronized (t) {
      if (!isAlive()) {
        return;
      }

      // guaranteed not to overflow
      long nanosToWait = millis * NANOS_PER_MILLI + nanos;

      // wait until this thread completes or the timeout has elapsed
      long start = System.nanoTime();
      while (true) {
        t.wait(millis, nanos);
        if (!isAlive()) {
          break;
        }
        long nanosElapsed = System.nanoTime() - start;
        long nanosRemaining = nanosToWait - nanosElapsed;
        if (nanosRemaining <= 0) {
          break;
        }
        millis = nanosRemaining / NANOS_PER_MILLI;
        nanos = (int) (nanosRemaining - millis * NANOS_PER_MILLI);
      }
    }
  }
Beispiel #6
0
  public void sortBubbleClassic() {
    int currentPosition;
    int maxPosition;
    int temp;
    switchCount = 0;
    compareCount = 0;
    timeAmount = System.nanoTime();

    for (maxPosition = array.length - 1; maxPosition >= 0; maxPosition--) {
      for (currentPosition = 0; currentPosition < maxPosition; currentPosition++) {
        compareCount++;
        if (array[currentPosition] > array[currentPosition + 1]) {
          temp = array[currentPosition];
          array[currentPosition] = array[currentPosition + 1];
          array[currentPosition + 1] = temp;
          switchCount++;
        }
      }
    }
    timeAmount = System.nanoTime() - timeAmount;
    assert (validate());
    return;
  }
Beispiel #7
0
  public static void performTest(final Map<String, Integer> m) throws Exception {

    out.println("Test started for: " + m.getClass());
    long avgTime = 0;
    for (int i = 0; i < 5; i++) {

      long startTime = System.nanoTime();
      ExecutorService exService = Executors.newFixedThreadPool(POOL_SIZE);

      for (int j = 0; j < POOL_SIZE; j++) {
        exService.execute(
            new Runnable() {
              @SuppressWarnings("unused")
              public void run() {
                for (int i = 0; i < 500000; i++) {
                  Integer randomNum = (int) Math.ceil(Math.random() * 550000);
                  // Retrieve value. We are not using it anywhere
                  Integer value = m.get(String.valueOf(randomNum));
                  // Put value
                  m.put(String.valueOf(randomNum), randomNum);
                }
              }
            });
      }

      // Make sure executor stops
      exService.shutdown();
      // Blocks until all tasks have completed execution after a shutdown request
      exService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);

      long entTime = System.nanoTime();
      long totalTime = (entTime - startTime) / 1000000L;
      avgTime += totalTime;
      out.println("500K entried added/retrieved in " + totalTime + " ms");
    }
    out.println("For " + m.getClass() + " the average time is " + avgTime / 5 + " ms\n");
  }
Beispiel #8
0
    @Override
    public void run() {
      Process.setThreadPriority(Process.THREAD_PRIORITY_URGENT_AUDIO);
      Logging.d(TAG, "AudioRecordThread" + WebRtcAudioUtils.getThreadInfo());
      assertTrue(audioRecord.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING);

      long lastTime = System.nanoTime();
      while (keepAlive) {
        int bytesRead = audioRecord.read(byteBuffer, byteBuffer.capacity());
        if (bytesRead == byteBuffer.capacity()) {
          if (microphoneMute) {
            byteBuffer.clear();
            byteBuffer.put(emptyBytes);
          }
          nativeDataIsRecorded(bytesRead, nativeAudioRecord);
        } else {
          Logging.e(TAG, "AudioRecord.read failed: " + bytesRead);
          if (bytesRead == AudioRecord.ERROR_INVALID_OPERATION) {
            keepAlive = false;
          }
        }
        if (DEBUG) {
          long nowTime = System.nanoTime();
          long durationInMs = TimeUnit.NANOSECONDS.toMillis((nowTime - lastTime));
          lastTime = nowTime;
          Logging.d(TAG, "bytesRead[" + durationInMs + "] " + bytesRead);
        }
      }

      try {
        if (audioRecord != null) {
          audioRecord.stop();
        }
      } catch (IllegalStateException e) {
        Logging.e(TAG, "AudioRecord.stop failed: " + e.getMessage());
      }
    }
Beispiel #9
0
  private static void runJaversion(Integer[] data) {
    out.println("Javersion PersistentHashMap");
    PersistentHashMap<Integer, Integer> jmap = PersistentHashMap.empty();
    // warmup
    for (Integer v : data) {
      jmap = jmap.assoc(v, v);
    }
    jmap = null;
    System.gc();

    long begin = System.nanoTime();
    for (int i = 1; i <= data.length; i++) {
      start();
      jmap = PersistentHashMap.empty();
      for (int j = 0; j < i; j++) {
        jmap = jmap.assoc(data[j], data[j]);
      }
      for (int j = 0; j < i; j++) {
        jmap = jmap.dissoc(data[j]);
      }
      out.println(end());
    }
    out.println(String.format("\n%s", System.nanoTime() - begin));
  }
Beispiel #10
0
  private static void runJavaTree(Integer[] data) {
    out.println("Java TreeMap");
    TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
    // warmup
    for (Integer v : data) {
      map.put(v, v);
    }
    map = null;
    //        System.gc();

    long begin = System.nanoTime();
    for (int i = 1; i <= data.length; i++) {
      start();
      map = new TreeMap<Integer, Integer>();
      for (int j = 0; j < i; j++) {
        map.put(data[j], data[j]);
      }
      for (int j = 0; j < i; j++) {
        map.remove(data[j]);
      }
      out.println(end());
    }
    out.println(String.format("\n%s", System.nanoTime() - begin));
  }
Beispiel #11
0
 private void sleepFor(long startNanos, long durationNanos) {
   while (true) {
     long elapsedNanos = System.nanoTime() - startNanos;
     long sleepNanos = durationNanos - elapsedNanos;
     long sleepMills = sleepNanos / NANOS_PER_MILLI;
     if (sleepMills <= 0) {
       return;
     }
     try {
       Thread.sleep(sleepMills);
     } catch (InterruptedException e) {
       if (!isRunning()) {
         return;
       }
     }
   }
 }
Beispiel #12
0
 @FindBugsSuppressWarnings("FI_EXPLICIT_INVOCATION")
 private void doFinalize(FinalizerReference<?> reference) {
   FinalizerReference.remove(reference);
   Object object = reference.get();
   reference.clear();
   try {
     finalizingStartedNanos = System.nanoTime();
     finalizingObject = object;
     synchronized (FinalizerWatchdogDaemon.INSTANCE) {
       FinalizerWatchdogDaemon.INSTANCE.notify();
     }
     object.finalize();
   } catch (Throwable ex) {
     // The RI silently swallows these, but Android has always logged.
     System.logE("Uncaught exception thrown by finalizer", ex);
   } finally {
     finalizingObject = null;
   }
 }
Beispiel #13
0
  public static void main(String args[]) throws InterruptedException, IOException {
    int i, j;
    String serverInetAddress = "localhost";

    String server1AddressString = "10.10.1.1";
    InetAddress server1Address = InetAddress.getByName(server1AddressString);
    String server2AddressString = "10.10.2.2";
    InetAddress server2Address = InetAddress.getByName(server2AddressString);
    String server3AddressString = "10.10.3.2";
    InetAddress server3Address = InetAddress.getByName(server3AddressString);
    String server4AddressString = "localhost";
    InetAddress server4Address = InetAddress.getByName(server4AddressString);

    DatagramSocket skt;
    {
      skt = new DatagramSocket(PORT_NUMBER_CLIENT); // socket used to listen and write
      InetAddress host = InetAddress.getByName(serverInetAddress);
      int serversocket = S1.PORT_NUMBER_SERVER;

      String msg = "Send file size";
      byte[] b = msg.getBytes();

      // dummy assignments - not used anywhere
      int filesize = 1;
      DatagramPacket reply, request;
      reply = new DatagramPacket(b, b.length, host, serversocket);
      request = new DatagramPacket(b, b.length, host, serversocket);

      for (i = 1; i <= 3; i++) {
        // defining a packet called request with parameters b(msg in bytes), b.length, host Internet
        // address and socket number
        if (i == 1) {
          host = server1Address;
        } else if (i == 2) {
          host = server2Address;
        } else if (i == 3) {
          host = server3Address;
        }
        request = new DatagramPacket(b, b.length, host, serversocket);
        // System.out.println("request sent from client to server");
        Thread.sleep(S1.PAUSE_DURATION); // for error checks

        // Sending the packet- for getting the file size
        skt.send(request);

        //		getting reply from
        // server........................................................................................
        byte[] buffer =
            new byte
                [S1.PACKET_SIZE]; // apparently the size of data packet at the receiving side needs
                                  // to be bigger than the size of incoming datapacket
        reply = new DatagramPacket(buffer, buffer.length);

        // receiving packet from server - contatining filesize
        skt.receive(reply);
        // System.out.println("Response Received from server");

        // System.out.println("on Client: - filesize= "+new String(reply.getData()));
        filesize = Integer.parseInt(new String(reply.getData()).trim());
        // System.out.println("on Client: - filesize= "+filesize);
        Thread.sleep(S1.PAUSE_DURATION);
      }

      // here the client know the size of the file
      // Find the number of times it must make iterations - dividing filesize by packet_size
      // Request that many packets from server
      String[] buffer_string = new String[BUFFER_SIZE_CLIENT];
      float delay[] = new float[filesize / S1.PACKET_SIZE];
      System.out.println(filesize);
      System.out.println(S1.PACKET_SIZE);
      System.out.println(filesize / S1.PACKET_SIZE);
      Thread.sleep(2000);
      byte[] buffer = new byte[S1.PACKET_SIZE];
      for (i = 0; i < filesize / S1.PACKET_SIZE; i++) {
        if (i % 100 != 0) {
          // System.out.print(" "+i);
        } else {
          System.out.println(" " + i);
        }

        msg = String.valueOf(i);
        b = msg.getBytes();

        if (i % 3 == 0) {
          host = server1Address;
        } else if (i % 3 == 1) {
          host = server2Address;
        } else if (i % 3 == 2) {
          host = server3Address;
        }

        request = new DatagramPacket(b, b.length, host, serversocket);

        skt.send(request);
        delay[i] = System.nanoTime();
        Thread.sleep(10);
        skt.receive(reply);
        delay[i] = System.nanoTime() - delay[i];
        delay[i] = delay[i] / (1000000);
        /*
        if(empty_index<BUFFER_SIZE_CLIENT)
        {
        	buffer_string[empty_index]=new String(reply.getData());
        	empty_index++;
        }
        else
        {
        	for(j=0;j<BUFFER_SIZE_CLIENT-1;j++)
        	{
        		buffer_string[j]=buffer_string[j+1];
        	}
        	buffer_string[BUFFER_SIZE_CLIENT-1]=new String(reply.getData());
        }*/

        // display_buffer(buffer_string);
      }
      Arrays.sort(delay);
      float delay2[] = new float[filesize / S1.PACKET_SIZE];
      for (i = 0; i < delay2.length; i++) {
        delay2[i] = delay[delay.length - i - 1];
      }
      // delay2 stores the array in descending values

      float[] Sk = new float[filesize / S1.PACKET_SIZE];
      Sk[0] = (float) 0.0;

      for (i = 1; i < filesize / S1.PACKET_SIZE; i++) {
        for (j = 1; j <= i; j++) {
          Sk[i] = Sk[i] + delay2[j];
        }
        Sk[i] = Sk[i] / (10 * i);
      }
      make_output(Sk);
      System.out.format(
          "Sk at 2=%f\n,10=%f\n,20=%f\n,100=%f\n and 30000=%f\n ",
          Sk[1], Sk[9], Sk[19], Sk[99], Sk[29999]);
      // display_buffer(buffer_string);
      skt.close();
    }
  }
Beispiel #14
0
 private static long end() {
   return System.nanoTime() - start;
 }
Beispiel #15
0
 private static void start() {
   start = System.nanoTime();
 }