Created
October 3, 2016 23:04
-
-
Save apangin/39677210c09d0c2abc82178ed1c93371 to your computer and use it in GitHub Desktop.
Java HighResolutionTimer hack for Windows
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javax.sound.midi.MidiDevice; | |
import javax.sound.midi.MidiUnavailableException; | |
import javax.sound.midi.spi.MidiDeviceProvider; | |
public class HighResolutionTimer { | |
private static final MidiDevice midiDevice = getMidiOutDevice(); | |
private static MidiDevice getMidiOutDevice() { | |
MidiDeviceProvider provider = new com.sun.media.sound.MidiOutDeviceProvider(); | |
MidiDevice.Info[] info = provider.getDeviceInfo(); | |
return info.length > 0 ? provider.getDevice(info[0]) : null; | |
} | |
public static synchronized void enable() { | |
if (midiDevice != null && !midiDevice.isOpen()) { | |
try { | |
midiDevice.open(); | |
} catch (MidiUnavailableException e) { | |
// ignore | |
} | |
} | |
} | |
public static synchronized void disable() { | |
if (midiDevice != null && midiDevice.isOpen()) { | |
midiDevice.close(); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.concurrent.locks.LockSupport; | |
public class MeasureTimerResolution { | |
private static double measureResolution() { | |
long startTime = System.nanoTime(); | |
LockSupport.parkNanos(1); | |
return (System.nanoTime() - startTime) / 1000000.0; | |
} | |
public static void main(String[] args) throws Exception { | |
HighResolutionTimer.enable(); | |
System.out.println("HighResolutionTimer enabled:"); | |
for (int i = 0; i < 10; i++) { | |
System.out.println(measureResolution()); | |
} | |
HighResolutionTimer.disable(); | |
System.out.println("HighResolutionTimer disabled:"); | |
for (int i = 0; i < 10; i++) { | |
System.out.println(measureResolution()); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
HighResolutionTimer enabled: | |
1.630574 | |
0.827902 | |
0.956192 | |
0.942081 | |
0.951061 | |
0.959614 | |
0.940797 | |
1.776398 | |
1.133233 | |
0.95491 | |
HighResolutionTimer disabled: | |
15.65017 | |
15.291812 | |
15.528722 | |
15.41882 | |
28.047746 | |
15.543689 | |
15.426944 | |
15.490235 | |
15.504774 | |
15.739546 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment