Archivos por Etiqueta: speed

OpenSSH: Speed UP SSH Connections

Para acelerar las conexiones recurrentes en OpenSSH:

En el cliente:

# /etc/ssh/ssh_config
Host *
    ControlMaster auto
    ControlPath /dev/shm/.ssh-mux_%u_%r@%h:%p
    ControlPersist 600
    # You can set this to "no" if you trust your LAN/DNS
    CheckHostIP no

En el server:

# /etc/ssh/sshd_config
UseDNS no

Rerefencias:
ssh_config
sshd_config

Anuncios

Java: WallClock versus System.currentTimeMillis

Como de costoso es llamar a System.currentTimeMillis()?

Si tenemos una función dependiente del tiempo y a esa funcion la llamamos, digamos… 500.000.000 veces y tarda 9911ms; hay alguna manera de hacer que sea más rápido? Bueno, si eludimos la llamada al reloj del sistema mediante un pequeño cache puede que ganemos unos segundos…

Esto sería el esqueleto del sistema, un thread que actualiza el reloj a intervalos regulares y una funcion q devuelve el último valor conocido:

public class WallClock implements Runnable {
  private static final int clockLatency = 1;  // WallClock time refresh (millis)
  private static WallClock self = null;       // Singleton
  private volatile long lastTimeMillis = 0L;  // Last time cached from SystemClock
  private volatile Thread clocker = null;     // WallClock Thread

  public static synchronized WallClock getInstance() {
    if (self == null) {
      self = new WallClock();
      self.init();
    }
    return self;
  }

  public long currentTimeMillis() {
    return lastTimeMillis;
  }

  private void init() {
    if (clocker == null) {
      clocker = new Thread(this);
      clocker.setDaemon(true);
      clocker.start();
    }
  }
  public void destroy() {
    clocker.interrupt();
  }

  /**
   * Run, baby, run
   */
  public void run() {
    try {
      while (!Thread.currentThread().isInterrupted()) {
        lastTimeMillis = System.currentTimeMillis();
        Thread.sleep(clockLatency);
      }
    } catch (InterruptedException ie) {
      /* Allow thread to exit */
    } finally {
      clocker = null;
    }
  }
}

Y cuanto tiempo ganamos con esta aproximación?

  public static void main(final String[] args) throws Throwable {
    final int TOTAL = 500000000;
    long ax = 0, ts = 0;
    //
    ts = System.currentTimeMillis();
    for (int i = 0; i < TOTAL; i++) {
      ax += (System.currentTimeMillis() & 0xF);
    }
    System.out.println("SystemClock: " + (System.currentTimeMillis() - ts) + "ms");
    //
    final WallClock wc = WallClock.getInstance();
    ts = System.currentTimeMillis();
    for (int i = 0; i < TOTAL; i++) {
      ax += (wc.currentTimeMillis() & 0xF);
    }
    System.out.println("WallClock: " + (System.currentTimeMillis() - ts) + "ms");
    if ((ax > 0) || (ts > 0)) // Dummy (always true)
      wc.destroy();
  }
SystemClock: 9911ms
WallClock..: 1820ms

El resultado es un aumento de la velocidad x5, el precio q se paga es tener un thread en background y algo de perdida de precision en los valores del reloj, pero es lo que tienen los caches.

Source code: WallClock.java

Java: Speed Limit on InputStream/OutputStream

Si necesitas reducir la velocidad de un InputStream/OutputStream de un modo sencillo, esta es la solución!

public class ThrottleStream {
	protected final int speedLimitBytesSecond;
	protected int currentTransferredBytes = 0;
	protected long lastTimeStampSeconds = 0;

	protected ThrottleStream(final int maxSpeedInKilobytesPerSecond) {
		this.speedLimitBytesSecond = maxSpeedInKilobytesPerSecond * 1024;
	}

	protected void addAndWait(final int transferred) throws IOException {
		long now = System.currentTimeMillis() / 1000;
		if (now != lastTimeStampSeconds) {
			currentTransferredBytes = 0;
			lastTimeStampSeconds = now;
		}
		currentTransferredBytes += transferred;
		if (currentTransferredBytes >= speedLimitBytesSecond) {
			try {
				while (true) {
					Thread.sleep(10);
					now = System.currentTimeMillis() / 1000;
					if (now != lastTimeStampSeconds) {
						currentTransferredBytes = 0;
						lastTimeStampSeconds = now;
						break;
					}
				}
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
				throw new IOException(e);
			}
		}
	}

	/**
	 * Speed Limit de un InputStream
	 */
	public static class ThrottleInputStream extends FilterInputStream {
		final ThrottleStream limit;

		public ThrottleInputStream(final InputStream in, 
				final int maxSpeedInKilobytesPerSecond) {
			super(in);
			limit = new ThrottleStream(maxSpeedInKilobytesPerSecond);
		}

		@Override
		public int read() throws IOException {
			final int read = super.read();
			limit.addAndWait(read);
			return read;
		}

		@Override
		public int read(final byte[] b) throws IOException {
			final int read = super.read(b);
			limit.addAndWait(read);
			return read;
		}

		@Override
		public int read(final byte[] b, final int off, final int len) 
				throws IOException {
			final int read = super.read(b, off, len);
			limit.addAndWait(read);
			return read;
		}
	}

	/**
	 * Speed Limit de un OutputStream
	 */
	public static class ThrottleOutputStream extends FilterOutputStream {
		final ThrottleStream limit;

		public ThrottleOutputStream(final OutputStream out, 
				final int maxSpeedInKilobytesPerSecond) {
			super(out);
			limit = new ThrottleStream(maxSpeedInKilobytesPerSecond);
		}

		@Override
		public void write(final int b) throws IOException {
			super.write(b);
			limit.addAndWait(1);
		}

		@Override
		public void write(final byte[] b) throws IOException {
			super.write(b);
			limit.addAndWait(b.length);
		}

		@Override
		public void write(final byte[] b, final int off, final int len) 
				throws IOException {
			super.write(b, off, len);
			limit.addAndWait(len);
		}
	}
}

Source code: ThrottleStream.java

A %d blogueros les gusta esto: