java.util.date - Java: Speeding up and slowing down time -
i'm trying figure out logic set arbitrary time, , have time "play back" @ different speeds (like .5x or 4x real time).
here logic have far, playback time @ normal speed:
import java.util.calendar; public class clock { long delta; private float speed = 1f; public clock(calendar startingtime) { delta = system.currenttimemillis()-startingtime.gettimeinmillis(); } private calendar adjustedtime() { calendar cal = calendar.getinstance(); cal.settimeinmillis(system.currenttimemillis()-delta); return cal; } public void setplaybackspeed(float speed){ this.speed = speed; } public static void main(string[] args){ calendar calendar = calendar.getinstance(); calendar.set(2010, 4, 4, 4, 4, 4); clock clock = new clock(calendar); while(true){ system.out.println(clock.adjustedtime().gettime()); try { thread.sleep(1000); } catch (interruptedexception e) { // todo auto-generated catch block e.printstacktrace(); } } } }
i'm having trouble figuring out "speed" attribute needs used in logic.
the following code gives example of how design such clock, has internal state of double spped
, long starttime
. exposes publish method gettime()
, return adjusted time in millisecond since midnight, jan 1st, 1970. note adjustment happens after starttime
.
the formula calculate adjusted time simple. first take real timedelta subtracting currenttimemillis()
starttime
, multiply value speed
adjusted timedelta, add starttime
result.
public class variablespeedclock { private double speed; private long starttime; public variablespeedclock(double speed) { this(speed, system.currenttimemillis()); } public variablespeedclock(double speed, long starttime) { this.speed = speed; this.starttime = starttime; } public long gettime () { return (long) ((system.currenttimemillis() - this.starttime) * this.speed + this.starttime); } public static void main(string [] args) throws interruptedexception { long st = system.currenttimemillis(); variablespeedclock vsc = new variablespeedclock(2.3); thread.sleep(1000); system.out.println(vsc.gettime() - st); system.out.println(system.currenttimemillis() - st); } }
Comments
Post a Comment