예제 #1
1
  static void serTest(Map s, int size) throws Exception {
    if (!(s instanceof Serializable)) return;
    System.out.print("Serialize              : ");

    for (int i = 0; i < size; i++) {
      s.put(new Integer(i), Boolean.TRUE);
    }

    long startTime = System.currentTimeMillis();

    FileOutputStream fs = new FileOutputStream("MapCheck.dat");
    ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(fs));
    out.writeObject(s);
    out.close();

    FileInputStream is = new FileInputStream("MapCheck.dat");
    ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(is));
    Map m = (Map) in.readObject();

    long endTime = System.currentTimeMillis();
    long time = endTime - startTime;

    System.out.print(time + "ms");

    if (s instanceof IdentityHashMap) return;
    reallyAssert(s.equals(m));
  }
예제 #2
0
 /**
  * This method runs the Runnable and measures how long it takes.
  *
  * @param r is the Runnable for the task that we want to measure
  * @return the time it took to execute this task
  */
 public static long time(Runnable r) {
   long time = -System.currentTimeMillis();
   r.run();
   time += System.currentTimeMillis();
   System.out.println("Took " + time + "ms");
   return time;
 }
예제 #3
0
  public static void main(String[] args) {
    long head = 0;
    num_thread = Integer.parseInt(args[0]);
    long total = Long.parseLong(args[1]);
    section = total / ((long) num_thread);
    sectionHead = new long[num_thread];

    long start = System.currentTimeMillis();
    Thread[] threads = new Thread[num_thread];
    for (int i = 0; i < num_thread; i++) {
      threads[i] = new Thread(new CoinFlip(i));
      threads[i].start();
    }
    for (int j = 0; j < num_thread; j++) {
      try {
        threads[j].join();
        head = head + sectionHead[j];
      } catch (InterruptedException e) {
        System.out.println(
            "Thread interrupted.  Exception: " + e.toString() + " Message: " + e.getMessage());
        return;
      }
    }
    long end = System.currentTimeMillis();

    System.out.println(head + " heads in " + args[1] + " coin tosses");
    System.out.println("Elapsed time: " + ((end - start)) + "ms");
  }
예제 #4
0
  /** 基类实现消息监听接口,加上打印metaq监控日志的方法 */
  @Override
  public ConsumeConcurrentlyStatus consumeMessage(
      List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
    long startTime = System.currentTimeMillis();
    logger.info("receive_message:{}", msgs.toString());
    if (msgs == null || msgs.size() < 1) {
      logger.error("receive empty msg!");
      return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }

    List<Serializable> msgList = new ArrayList<>();
    for (MessageExt message : msgs) {
      msgList.add(decodeMsg(message));
    }

    final int reconsumeTimes = msgs.get(0).getReconsumeTimes();
    MsgObj msgObj = new MsgObj();
    msgObj.setReconsumeTimes(reconsumeTimes);
    msgObj.setMsgList(msgList);
    msgObj.setContext(context);
    context.setDelayLevelWhenNextConsume(getDelayLevelWhenNextConsume(reconsumeTimes));

    ConsumeConcurrentlyStatus status = doConsumeMessage(msgObj);
    logger.info(
        "ConsumeConcurrentlyStatus:{}|cost:{}", status, System.currentTimeMillis() - startTime);
    return status;
  }
 private boolean handshake() {
   boolean res;
   long started = System.currentTimeMillis();
   do {
     try {
       res = myPydevConsoleCommunication.handshake();
     } catch (XmlRpcException ignored) {
       res = false;
     }
     if (res) {
       break;
     } else {
       long now = System.currentTimeMillis();
       if (now - started > APPROPRIATE_TO_WAIT) {
         break;
       } else {
         try {
           Thread.sleep(100);
         } catch (InterruptedException ignored) {
         }
       }
     }
   } while (true);
   return res;
 }
    /** {@inheritDoc} */
    @Override
    public Serializable execute() {
      synchronized (mux) {
        execCnt++;
      }

      if (log.isInfoEnabled()) log.info("Executing job: " + jobCtx.getJobId());

      long now = System.currentTimeMillis();

      while (!isCancelled && now < thresholdTime) {
        synchronized (mux) {
          try {
            mux.wait(thresholdTime - now);
          } catch (InterruptedException ignored) {
            // No-op.
          }
        }

        now = System.currentTimeMillis();
      }

      synchronized (mux) {
        return isCancelled ? 1 : 0;
      }
    }
    protected void preCache(List<Position> grid, Position centerPosition)
        throws InterruptedException {
      // Pre-cache the tiles that will be needed for the intersection calculations.
      double n = 0;
      final long start = System.currentTimeMillis();
      for (Position gridPos : grid) // for each grid point.
      {
        final double progress = 100 * (n++ / grid.size());
        terrain.cacheIntersectingTiles(centerPosition, gridPos);

        SwingUtilities.invokeLater(
            new Runnable() {
              public void run() {
                progressBar.setValue((int) progress);
                progressBar.setString(null);
              }
            });
      }

      SwingUtilities.invokeLater(
          new Runnable() {
            public void run() {
              progressBar.setValue(100);
            }
          });

      long end = System.currentTimeMillis();
      System.out.printf(
          "Pre-caching time %d milliseconds, cache usage %f, tiles %d\n",
          end - start, terrain.getCacheUsage(), terrain.getNumCacheEntries());
    }
 // BEGIN KAWIGIEDIT TESTING
 // Generated by KawigiEdit-pf 2.3.0
 private static boolean KawigiEdit_RunTest(int testNum, int p0, boolean hasAnswer, int p1) {
   System.out.print("Test " + testNum + ": [" + p0);
   System.out.println("]");
   EmoticonsDiv1 obj;
   int answer;
   obj = new EmoticonsDiv1();
   long startTime = System.currentTimeMillis();
   answer = obj.printSmiles(p0);
   long endTime = System.currentTimeMillis();
   boolean res;
   res = true;
   System.out.println("Time: " + (endTime - startTime) / 1000.0 + " seconds");
   if (hasAnswer) {
     System.out.println("Desired answer:");
     System.out.println("\t" + p1);
   }
   System.out.println("Your answer:");
   System.out.println("\t" + answer);
   if (hasAnswer) {
     res = answer == p1;
   }
   if (!res) {
     System.out.println("DOESN'T MATCH!!!!");
   } else if ((endTime - startTime) / 1000.0 >= 2) {
     System.out.println("FAIL the timeout");
     res = false;
   } else if (hasAnswer) {
     System.out.println("Match :-)");
   } else {
     System.out.println("OK, but is it right?");
   }
   System.out.println("");
   return res;
 }
예제 #9
0
    /**
     * Sends a MERGE_REQ to all coords and populates a list of MergeData (in merge_rsps). Returns
     * after coords.size() response have been received, or timeout msecs have elapsed (whichever is
     * first).
     *
     * <p>If a subgroup coordinator rejects the MERGE_REQ (e.g. because of participation in a
     * different merge), <em>that member will be removed from coords !</em>
     *
     * @param coords A map of coordinatgor addresses and associated membership lists
     * @param new_merge_id The new merge id
     * @param timeout Max number of msecs to wait for the merge responses from the subgroup coords
     */
    private boolean getMergeDataFromSubgroupCoordinators(
        Map<Address, Collection<Address>> coords, MergeId new_merge_id, long timeout) {
      boolean gotAllResponses;
      long start = System.currentTimeMillis();
      merge_rsps.reset(coords.keySet());
      if (log.isDebugEnabled())
        log.debug(gms.local_addr + ": sending MERGE_REQ to " + coords.keySet());

      for (Map.Entry<Address, Collection<Address>> entry : coords.entrySet()) {
        Address coord = entry.getKey();
        Collection<Address> mbrs = entry.getValue();
        Message msg = new Message(coord, null, null);
        msg.setFlag(Message.OOB);
        GMS.GmsHeader hdr = new GMS.GmsHeader(GMS.GmsHeader.MERGE_REQ, mbrs);
        hdr.mbr = gms.local_addr;
        hdr.merge_id = new_merge_id;
        msg.putHeader(gms.getId(), hdr);
        gms.getDownProtocol().down(new Event(Event.MSG, msg));
      }

      // wait until num_rsps_expected >= num_rsps or timeout elapsed
      merge_rsps.waitForAllResponses(timeout);
      gotAllResponses = merge_rsps.hasAllResponses();
      long stop = System.currentTimeMillis();
      if (log.isDebugEnabled())
        log.debug(
            gms.local_addr
                + ": collected "
                + merge_rsps.size()
                + " merge response(s) in "
                + (stop - start)
                + " ms");
      return gotAllResponses;
    }
예제 #10
0
  /**
   * Sends the new view and digest to all subgroup coordinors in coords. Each coord will in turn
   *
   * <ol>
   *   <li>broadcast the new view and digest to all the members of its subgroup (MergeView)
   *   <li>on reception of the view, if it is a MergeView, each member will set the digest and
   *       install the new view
   * </ol>
   */
  private void sendMergeView(
      Collection<Address> coords, MergeData combined_merge_data, MergeId merge_id) {
    if (coords == null || combined_merge_data == null) return;

    View view = combined_merge_data.view;
    Digest digest = combined_merge_data.digest;
    if (view == null || digest == null) {
      if (log.isErrorEnabled())
        log.error("view or digest is null, cannot send consolidated merge view/digest");
      return;
    }

    if (log.isDebugEnabled())
      log.debug(
          gms.local_addr + ": sending merge view " + view.getVid() + " to coordinators " + coords);

    gms.merge_ack_collector.reset(coords);
    int size = gms.merge_ack_collector.size();
    long timeout = gms.view_ack_collection_timeout;

    long start = System.currentTimeMillis();
    for (Address coord : coords) {
      Message msg = new Message(coord, null, null);
      GMS.GmsHeader hdr = new GMS.GmsHeader(GMS.GmsHeader.INSTALL_MERGE_VIEW);
      hdr.view = view;
      hdr.my_digest = digest;
      hdr.merge_id = merge_id;
      msg.putHeader(gms.getId(), hdr);
      gms.getDownProtocol().down(new Event(Event.MSG, msg));
    }

    // [JGRP-700] - FLUSH: flushing should span merge
    // if flush is in stack wait for acks from separated island coordinators
    if (gms.flushProtocolInStack) {
      try {
        gms.merge_ack_collector.waitForAllAcks(timeout);
        long stop = System.currentTimeMillis();
        if (log.isTraceEnabled())
          log.trace(
              "received all ACKs ("
                  + size
                  + ") for merge view "
                  + view
                  + " in "
                  + (stop - start)
                  + "ms");
      } catch (TimeoutException e) {
        log.warn(
            gms.local_addr
                + ": failed to collect all ACKs for merge ("
                + size
                + ") for view "
                + view
                + " after "
                + timeout
                + "ms, missing ACKs from "
                + gms.merge_ack_collector.printMissing());
      }
    }
  }
예제 #11
0
    public List<PingData> get(long timeout) throws InterruptedException {
      long start_time = System.currentTimeMillis(), time_to_wait = timeout;

      promise.getLock().lock();
      try {
        while (time_to_wait > 0 && !promise.hasResult()) {
          // if num_expected_srv_rsps > 0, then it overrides num_expected_rsps
          if (num_expected_srv_rsps > 0) {
            int received_srv_rsps = getNumServerResponses(ping_rsps);
            if (received_srv_rsps >= num_expected_srv_rsps)
              return new LinkedList<PingData>(ping_rsps);
          } else if (ping_rsps.size() >= num_expected_rsps) {
            return new LinkedList<PingData>(ping_rsps);
          }

          if (break_on_coord_rsp && containsCoordinatorResponse(ping_rsps))
            return new LinkedList<PingData>(ping_rsps);

          promise.getCond().await(time_to_wait, TimeUnit.MILLISECONDS);
          time_to_wait = timeout - (System.currentTimeMillis() - start_time);
        }
        return new LinkedList<PingData>(ping_rsps);
      } finally {
        promise.getLock().unlock();
      }
    }
예제 #12
0
  /**
   * An event is to be sent down the stack. The layer may want to examine its type and perform some
   * action on it, depending on the event's type. If the event is a message MSG, then the layer may
   * need to add a header to it (or do nothing at all) before sending it down the stack using <code>
   * PassDown</code>. In case of a GET_ADDRESS event (which tries to retrieve the stack's address
   * from one of the bottom layers), the layer may need to send a new response event back up the
   * stack using <code>up_prot.up()</code>. The PING protocol is interested in several different
   * down events, Event.FIND_INITIAL_MBRS - sent by the GMS layer and expecting a GET_MBRS_OK
   * Event.TMP_VIEW and Event.VIEW_CHANGE - a view change event Event.BECOME_SERVER - called after
   * client has joined and is fully working group member Event.CONNECT, Event.DISCONNECT.
   */
  @SuppressWarnings("unchecked")
  public Object down(Event evt) {

    switch (evt.getType()) {
      case Event.FIND_INITIAL_MBRS: // sent by GMS layer
      case Event.FIND_ALL_VIEWS:
        // sends the GET_MBRS_REQ to all members, waits 'timeout' ms or until 'num_initial_members'
        // have been retrieved
        long start = System.currentTimeMillis();
        boolean find_all_views = evt.getType() == Event.FIND_ALL_VIEWS;
        Promise<JoinRsp> promise = (Promise<JoinRsp>) evt.getArg();
        List<PingData> rsps = find_all_views ? findAllViews(promise) : findInitialMembers(promise);
        long diff = System.currentTimeMillis() - start;
        if (log.isTraceEnabled())
          log.trace("discovery took " + diff + " ms: responses: " + Util.printPingData(rsps));
        return rsps;

      case Event.TMP_VIEW:
      case Event.VIEW_CHANGE:
        List<Address> tmp;
        view = (View) evt.getArg();
        if ((tmp = view.getMembers()) != null) {
          synchronized (members) {
            members.clear();
            members.addAll(tmp);
          }
        }
        current_coord = !members.isEmpty() ? members.get(0) : null;
        is_coord = current_coord != null && local_addr != null && current_coord.equals(local_addr);

        return down_prot.down(evt);

      case Event.BECOME_SERVER: // called after client has joined and is fully working group member
        down_prot.down(evt);
        is_server = true;
        return null;

      case Event.SET_LOCAL_ADDRESS:
        local_addr = (Address) evt.getArg();
        return down_prot.down(evt);

      case Event.CONNECT:
      case Event.CONNECT_WITH_STATE_TRANSFER:
      case Event.CONNECT_USE_FLUSH:
      case Event.CONNECT_WITH_STATE_TRANSFER_USE_FLUSH:
        is_leaving = false;
        group_addr = (String) evt.getArg();
        Object ret = down_prot.down(evt);
        handleConnect();
        return ret;

      case Event.DISCONNECT:
        is_leaving = true;
        handleDisconnect();
        return down_prot.down(evt);

      default:
        return down_prot.down(evt); // Pass on to the layer below us
    }
  }
예제 #13
0
파일: Snake.java 프로젝트: szamani20/Snake
  private void doesEatRegime() {
    if (isEnd) return;

    if (Math.abs(blocks.peekFirst().getX() - regimeRectangle.getX()) < 10
        && Math.abs(blocks.peekFirst().getY() - regimeRectangle.getY()) < 10
        && System.currentTimeMillis() - currentTime <= 10000) {

      regimeRectangle.setX(1200);
      isRegime = false;
      ++score;
      scoreLabel.setText(String.valueOf(score));

      blocks.pollLast();
      blocks.pollLast();
      blocks.pollLast();

      group.getChildren().remove(rectangles.peekLast());
      rectangles.pollLast();
      group.getChildren().remove(rectangles.peekLast());
      rectangles.pollLast();
      group.getChildren().remove(rectangles.peekLast());
      rectangles.pollLast();
    }

    if (System.currentTimeMillis() - currentTime > 10000) {
      regimeRectangle.setX(1200);
      isRegime = false;
    }
  }
  public void createMap(int k) {
    // use myString

    String s1 = "";
    String s2 = "";
    double start = System.currentTimeMillis();
    for (int x = 0; x < myString.length(); x++) {
      if (s1.equals("")) {
        if ((myString.length() - x) < k) {
          s1 = myString.substring(x, myString.length());
          s1 += myString.substring(0, (k - s1.length()));
        } else s1 = myString.substring(x, x + k);
      }
      if ((myString.length() - x - 1) < k) {
        s2 = myString.substring(x + 1, myString.length());
        s2 += myString.substring(0, (k - s2.length()));
      } else s2 = myString.substring(x + 1, x + k + 1);
      if (!map.containsKey(s1)) {
        List<String> l = new ArrayList<String>();
        map.put(s1, l);
      }
      map.get(s1).add(s2);
      s1 = s2;
    }
    double end = System.currentTimeMillis();
    double time = (end - start) / 1000.0;
    System.out.println(time + " secs");
  }
예제 #15
0
  public void saveDataItems() {
    if (shouldLogData()) {
      try {
        if (ps == null) {
          synchronized (this) {
            if (ps == null) {
              String timestampString = LogTimestamp.getTimestampString();
              if (timestampString != null) {
                File logFile = new File(parentDirectory, timestampString + ".csv");
                ps = new PrintStream(new FileOutputStream(logFile));
                ps.print("time,timeSinceStart");
                writelist(ps, dataNames);
                startTime = System.currentTimeMillis();
              }
            }
          }
        }
        if (ps != null) {
          timeUpdated = (System.currentTimeMillis() - startTime);
          ps.print(getDate());
          ps.print(',');
          ps.print(timeUpdated);
          writelist(ps, dataValues);
          ps.flush();
          timeSinceLog = System.currentTimeMillis();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    dataValues.clear();
    dataNames.clear();
  }
예제 #16
0
 private CypherResult doExecuteQuery(String query, boolean canProfile) {
   long time = System.currentTimeMillis();
   Transaction tx = gdb.beginTx();
   javax.transaction.Transaction resumeTx;
   try {
     resumeTx = suspendTx(query);
     ExecutionResult result =
         canProfile ? executionEngine.profile(query) : executionEngine.execute(query);
     final Collection<Map<String, Object>> data = IteratorUtil.asCollection(result);
     time = System.currentTimeMillis() - time;
     resumeTransaction(resumeTx);
     CypherResult cypherResult =
         new CypherResult(
             result.columns(),
             data,
             result.getQueryStatistics(),
             time,
             canProfile ? result.executionPlanDescription() : null,
             prettify(query));
     tx.success();
     return cypherResult;
   } finally {
     tx.close();
   }
 }
예제 #17
0
 private void add(PooledFatPipe child) {
   long start = System.currentTimeMillis();
   while (true) {
     int fails = 0;
     for (int i = 0; i < inUse.length(); i++) {
       if (!inUse.compareAndSet(i, 0, 2)) {
         if (inUse.get(i) != 2) fails++;
       }
     }
     if (fails == 0) break;
     if (start + 100 < System.currentTimeMillis()) {
       logger.warn("unable to add cleanly " + toString());
       break;
     }
   }
   final AtomicIntegerArray updated = new AtomicIntegerArray(inUse.length() + 1);
   final List<Integer> needsReset = new ArrayList<>();
   for (int i = 0; i < inUse.length(); i++) {
     int value = inUse.get(i);
     if (value == 1) {
       updated.set(i, value);
       needsReset.add(i);
     }
   }
   final AtomicIntegerArray oldUse = inUse;
   inUse = updated;
   signals = new ChildSignalImpl[signals.length + poolSize];
   for (int i = 0; i < signals.length; i++) {
     signals[i] = new ChildSignalImpl(inUse, 0);
   }
   children = Arrays.copyOf(children, children.length + 1);
   children[children.length - 1] = child;
   scheduleReset(needsReset, oldUse, updated);
 }
예제 #18
0
 public byte[] enhance() {
   if (enhancing) throw new IllegalStateException("reenter enhance() call");
   enhancing = true;
   try {
     byte[] bytes = enhancedByteCode;
     if (null == bytes) {
       bytes = javaByteCode;
       if (null == bytes) bytes = compile();
       long start = System.currentTimeMillis();
       for (ITemplateClassEnhancer en : engine().templateClassEnhancers) {
         try {
           bytes = en.enhance(name(), bytes);
         } catch (Exception e) {
           logger.warn(e, "Error enhancing template class: %s", getKey());
         }
       }
       if (logger.isTraceEnabled()) {
         logger.trace(
             "%sms to enhance template class %s", System.currentTimeMillis() - start, getKey());
       }
       enhancedByteCode = bytes;
       engine().classCache.cacheTemplateClass(this);
     }
     for (TemplateClass embedded : embeddedClasses) {
       embedded.enhancedByteCode = null;
       embedded.enhance();
     }
     return bytes;
   } finally {
     enhancing = false;
   }
 }
예제 #19
0
  public void execute() {
    long startTime = System.currentTimeMillis();

    execute(configuration.getOperations());

    if (this.status == STATUS_RUNNING) {
      this.setStatus(STATUS_FINISHED);
    }

    // inform al listeners that execution is finished
    Iterator listenersIterator = this.scraperRuntimeListeners.iterator();
    while (listenersIterator.hasNext()) {
      ScraperRuntimeListener listener = (ScraperRuntimeListener) listenersIterator.next();
      listener.onExecutionEnd(this);
    }

    if (logger.isInfoEnabled()) {
      if (this.status == STATUS_FINISHED) {
        logger.info(
            "Configuration executed in " + (System.currentTimeMillis() - startTime) + "ms.");
      } else if (this.status == STATUS_STOPPED) {
        logger.info("Configuration stopped!");
      }
    }
  }
  @Override
  public EmotionResponse emotionJudge(EmotionRequest req) throws TException {
    long s1 = System.currentTimeMillis();
    String text = req.getText();
    List<Term> terms = ToAnalysis.parse(text);
    List<String> words = new ArrayList<>();
    for (Term term : terms) {
      words.add(term.getName());
    }
    //        logger.info("{} is cut into {}", text, words);

    double score = fbsc.classify(words);
    EmotionResponse response = new EmotionResponse();
    response.setReq(req);
    response.setScore(score);
    int emotion = 0;
    if (score > 0.5) {
      emotion = 1;
    } else if (score < -0.5) {
      emotion = 2;
    } else {
      emotion = 3;
    }
    response.setEmotion(emotion);
    long s2 = System.currentTimeMillis();
    logger.info("emotion: {}, used:{}ms", emotion, (s2 - s1));
    return response;
  }
예제 #21
0
 void updateMenus() {
   if (IJ.debugMode) {
     long start = System.currentTimeMillis();
     Menus.updateImageJMenus();
     IJ.log("Refresh Menus: " + (System.currentTimeMillis() - start) + " ms");
   } else Menus.updateImageJMenus();
 }
예제 #22
0
  public static void writeChemkinInputFile(ReactionSystem rs) {
    // #[ operation writeChemkinInputFile(ReactionModel,SystemSnapshot)

    StringBuilder result = new StringBuilder();
    result.append(writeChemkinHeader());
    result.append(writeChemkinElement());
    double start = System.currentTimeMillis();
    result.append(writeChemkinSpecies(rs.reactionModel, rs.initialStatus));
    result.append(writeChemkinThermo(rs.reactionModel));
    Global.chemkinThermo = Global.chemkinThermo + (System.currentTimeMillis() - start) / 1000 / 60;
    start = System.currentTimeMillis();
    result.append(writeChemkinPdepReactions(rs));
    Global.chemkinReaction =
        Global.chemkinReaction + (System.currentTimeMillis() - start) / 1000 / 60;

    String dir = System.getProperty("RMG.workingDirectory");
    if (!dir.endsWith("/")) dir += "/";
    dir += "software/reactorModel/";
    String file = "chemkin/chem.inp";

    try {
      FileWriter fw = new FileWriter(file);
      fw.write(result.toString());
      fw.close();
    } catch (Exception e) {
      System.out.println("Error in writing chemkin input file chem.inp!");
      System.out.println(e.getMessage());
      System.exit(0);
    }

    // #]
  }
예제 #23
0
 public Program compileFile(String fileName) {
   String code = "";
   String dummy;
   try {
     long ms = System.currentTimeMillis();
     long atAll = ms;
     BufferedReader r;
     if (fileName.compareToIgnoreCase("stdin") == 0) {
       owner.writeLn("Please type in your Prolog program. EOF is indicated by \"#\".");
       r = new BufferedReader(new InputStreamReader(System.in));
     } else r = new BufferedReader(new FileReader(fileName));
     do {
       dummy = r.readLine();
       if (dummy != null) {
         if (dummy.compareTo("#") == 0) break;
         code += " " + dummy;
       }
     } while (dummy != null);
     owner.debug("File Operations: " + (System.currentTimeMillis() - ms) + " ms.", -1);
     Program p = compile(code);
     return p;
   } catch (Exception io) {
     owner.writeLn("File \"" + fileName + "\" could not be opened.");
     return null;
   }
 } // end of PrologCompiler.compileFile(String)
예제 #24
0
  private final String readMSG(final int len)
      throws IOException, InterruptedException, MessagingNetworkException {
    if (len > 65000)
      ServerConnection.throwProtocolViolated("incoming message is too long: " + len + " bytes");
    byte[] b = new byte[len];
    InputStream is = getInputStream();
    synchronized (is) {
      long abortTime =
          System.currentTimeMillis() + 1000 * MSNMessagingNetwork.REQPARAM_SOCKET_TIMEOUT_SECONDS;
      int ofs = 0;

      while (ofs < len) {
        if (Thread.currentThread().isInterrupted()) throw new InterruptedIOException();
        int read = is.read(b, ofs, len - ofs);
        if (read < 0) read = 0;
        ofs += read;
        if (System.currentTimeMillis() > abortTime) throw new IOException("connection timed out");
        /*
        if (len >= buffer.length)
        {
          ...
          return ...;
        }
        int pos = findCRLF();
        if (pos != -1) break;
        fill(is, abortTime);
        */
      }

      String msg = new String(b, 0, len, "UTF-8");
      return msg;
    }
  }
예제 #25
0
 public void run() {
   try {
     uglyjoglhack();
     if (state == null)
       throw (new RuntimeException("State applier is still null after redraw"));
     synchronized (drawfun) {
       drawfun.notifyAll();
     }
     while (true) {
       long then = System.currentTimeMillis();
       int waited = 0;
       synchronized (drawfun) {
         while ((curdraw = bufdraw) == null) drawfun.wait();
         bufdraw = null;
         drawfun.notifyAll();
         waited += System.currentTimeMillis() - then;
       }
       CPUProfile.Frame curf = null;
       if (Config.profile) curdraw.pf = curf = rprof.new Frame();
       uglyjoglhack();
       if (curf != null) {
         curf.tick("aux");
         curf.fin();
       }
       long now = System.currentTimeMillis();
       waited += now - curdraw.doneat;
       ridle = (ridle * 0.95) + (((double) waited / ((double) (now - then))) * 0.05);
       curdraw = null;
     }
   } catch (InterruptedException e) {
     return;
   }
 }
예제 #26
0
  @Test
  public void optimizeRand() throws IOException {
    Optimizer optimizer = new Optimizer();
    long start;
    List<Vol> optimize;

    for (int i = 0; i < 1; i++) {
      List<Vol> list = randList(100000);

      start = System.currentTimeMillis();
      //            optimize = optimizer.optimize3(null, list);
      //            System.out.println(optimizer.formatString(optimize));
      //            System.out.println(System.currentTimeMillis() - start);
      //            System.out.println(Vol.toString(optimize));

      start = System.currentTimeMillis();
      List<Vol> optimize2 = optimizer.optimize4(list);
      long duration = System.currentTimeMillis() - start;
      System.out.println(optimizer.formatString(optimize2));
      System.out.println(duration);
      //            System.out.println(Vol.toString(optimize2));

      //
      // assertThat(Optimizer.price(optimize)).isLessThanOrEqualTo(Optimizer.price(optimize2));
      Iterator<Vol> iterator = optimize2.iterator();

      Vol vol = iterator.next();
      while (iterator.hasNext()) {
        Vol next = iterator.next();
        assertThat(vol.isNext(next)).isTrue();
        vol = next;
      }
    }
  }
예제 #27
0
    protected void addTimeStamp(ClassNode node) {
      if (node.getDeclaredField(Verifier.__TIMESTAMP)
          == null) { // in case if verifier visited the call already
        FieldNode timeTagField =
            new FieldNode(
                Verifier.__TIMESTAMP,
                ACC_PUBLIC | ACC_STATIC | ACC_SYNTHETIC,
                ClassHelper.long_TYPE,
                // "",
                node,
                new ConstantExpression(System.currentTimeMillis()));
        // alternatively, FieldNode timeTagField = SourceUnit.createFieldNode("public static final
        // long __timeStamp = " + System.currentTimeMillis() + "L");
        timeTagField.setSynthetic(true);
        node.addField(timeTagField);

        timeTagField =
            new FieldNode(
                Verifier.__TIMESTAMP__ + String.valueOf(System.currentTimeMillis()),
                ACC_PUBLIC | ACC_STATIC | ACC_SYNTHETIC,
                ClassHelper.long_TYPE,
                // "",
                node,
                new ConstantExpression((long) 0));
        // alternatively, FieldNode timeTagField = SourceUnit.createFieldNode("public static final
        // long __timeStamp = " + System.currentTimeMillis() + "L");
        timeTagField.setSynthetic(true);
        node.addField(timeTagField);
      }
    }
예제 #28
0
 /** @brief Check if it's time to save the auctions out yet. */
 private void checkSnapshot() {
   if ((mLastCheckpointed + mCheckpointFrequency) < System.currentTimeMillis()) {
     mLastCheckpointed = System.currentTimeMillis();
     saveAuctions();
     System.gc();
   }
 }
예제 #29
0
  static void test(String urlString) {
    try {
      long start = System.currentTimeMillis();
      System.out.println(" get " + urlString);

      AddePointDataReader reader = new AddePointDataReader(urlString);

      System.out.println(" took= " + (System.currentTimeMillis() - start) + " msec");
      System.out.println(reader.toString());

      System.out.println(" Param  Unit Scale");

      String[] params = reader.getParams();
      String[] units = reader.getUnits();
      int[] scales = reader.getScales();
      for (int i = 0; i < params.length; i++) {
        System.out.println(" " + params[i] + " " + units[i] + " " + scales[i]);
      }

      int[][] data = reader.getData();
      System.out.println(" nparams= " + params.length);
      System.out.println(" n= " + data.length);
      System.out.println(" m= " + data[0].length);

    } catch (AddeException e) {
      e.printStackTrace(); // To change body of catch statement use File | Settings | File
      // Templates.
    }
  }
  @Test
  public void testSendAndReceive() throws Exception {

    // Run the main controller
    ControllerRunner controllerRunner =
        new ControllerRunner(10, 9090, InetAddress.getLocalHost(), "127.0.0.1", 8008);
    controllerRunner.run();
    System.out.println("Controller running");

    Random random = new Random();
    int player = random.nextInt();

    // Connect a new controller and send test alarm
    Controller controller = new Controller(10);
    Socket connection1 = controller.connectTo(InetAddress.getLocalHost().getHostAddress(), 9090);
    Alarm alarm = new Alarm(player, System.currentTimeMillis(), new PlayerCause(player));
    controller.send(alarm, connection1);

    Controller controller2 = new Controller(10);
    Socket connection2 = controller2.connectTo(InetAddress.getLocalHost().getHostAddress(), 9090);
    long alarmtime = System.currentTimeMillis() + 500;
    Position position1 = new Position(player, System.currentTimeMillis(), 1, 2, 3);
    Position position2 = new Position(player, alarmtime, 100, 200, 300);
    controller2.send(position1, connection2);
    controller2.send(position2, connection2);
    controller2.send(new Request(player, DataType.ACCEL, -1, -1), connection2);
    controller2.send(new Request(player, DataType.POS, -1, -1), connection2);

    Thread.sleep(15000);
    List<Sendable> received = controller2.receive(connection2);
    List<Alarm> alarms = new ArrayList<Alarm>();
    List<Acceleration> accelerations = new ArrayList<Acceleration>();
    List<Position> positions = new ArrayList<Position>();

    // Distribute the sendable objects
    for (Sendable sendable : received) {
      if (sendable instanceof Alarm) {
        alarms.add((Alarm) sendable);

      } else if (sendable instanceof Service) {
        Service service = (Service) sendable;
        List<?> data = service.getData();
        for (Object o : data) {
          if (o instanceof Acceleration) {
            accelerations.add((Acceleration) o);
          } else if (o instanceof Position) {
            positions.add((Position) o);
          }
        }
      }
    }

    controller.disconnectFromClient(connection1);
    controller2.disconnectFromClient(connection2);

    assertTrue("Alarm was not sent from controller", alarms.size() >= 1);
    assertTrue("Acceleration not received from controller", accelerations.size() >= 1);
    assertTrue("Position 1 not contained in received positions", positions.contains(position1));
    assertTrue("Position 2 not contained in received positions", positions.contains(position2));
  }