code_junkie

System.currentTimeMillis vs System.nanoTime

Nov 12th, 2011
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. public static long nanoTime()
  2.  
  3. long startTime = System.nanoTime();
  4. // ... the code being measured ...
  5. long estimatedTime = System.nanoTime() - startTime;
  6.  
  7. private void test() {
  8. System.out.println("currentTimeMillis: "+System.currentTimeMillis());
  9. System.out.println("nanoTime : "+System.nanoTime());
  10. System.out.println();
  11.  
  12. testNano(false); // to sync with currentTimeMillis() timer tick
  13. for(int xa=0; xa<10; xa++) {
  14. testNano(true);
  15. }
  16. }
  17.  
  18. private void testNano(boolean shw) {
  19. long strMS=System.currentTimeMillis();
  20. long strNS=System.nanoTime();
  21. long curMS;
  22. while((curMS=System.currentTimeMillis()) == strMS) {
  23. if(shw) { System.out.println("Nano: "+(System.nanoTime()-strNS)); }
  24. }
  25. if(shw) { System.out.println("Nano: "+(System.nanoTime()-strNS)+", Milli: "+(curMS-strMS)); }
  26. }
  27.  
  28. long startTimeMillis = System.currentTimeMillis();
  29. long startTimeNanos = System.nanoTime();
  30.  
  31. long currentTimeMillis;
  32. while((currentTimeMillis = System.currentTimeMillis()) == startTimeMillis) {
  33. }
  34.  
  35.  
  36. System.out.println(System.nanoTime()-startTimeNanos);
  37. System.out.println(currentTimeMillis-startTimeMillis);
Add Comment
Please, Sign In to add comment