I'm interested in finding out the best way to measure the execution time of methods within a Java web service I'm working on.
The service will be deployed to multiple clients and hence run in multiple different production environments (clients tend to have varying setups as dictacted by their requirements), and its been decided the service should log the execution time for processing requests to provide some indication of possible performance issues.
So far, most of the suggestions (such as here & here) I've seen are to use System.currentTimeMillis()
at the beginning and end of the code I'm interested in and calculate elapsed time, but is that really the best solution to this problem for a production environment?
How suitable is System.currentTimeMillis()
for measuring method execution time, and are there any alternatives?
EDIT 0: To clarify, a key requirement is that this execution measurement should be deployed as part of the standard deployment to collect data so that it can be referred to should a performance related support issue be raised, as the service forms part of a complex system of new and legacy components
You can use the Spring Framework 'StopWatch' class:
You can even use AOP, this way you can profile code without changing it
Logging the time elapsed is fine, but you need to time it on the client side to really understand how long it's taking. That will additionally tell you how much time you're spending in data transfer which could indicate an I/O bottleneck.
System.currentTimeMillis() is suitable if your application will take more than 1 or 2 milliseconds to execute (although its precisions might be greater than the ms depending on your OS).
You might prefer using System.nanoTime() which can be fare more precise, but not to the nanosecond. Please note its precision also depends on your underlying system.
Both these methods are quite low-level (need you to manage timestamps) but have a lower overhead than more high-level API.