How to Log a Method's Execution Time Exactly in Milliseconds

How to log a method's execution time exactly in milliseconds?

NSDate *methodStart = [NSDate date];

/* ... Do whatever you need to do ... */

NSDate *methodFinish = [NSDate date];
NSTimeInterval executionTime = [methodFinish timeIntervalSinceDate:methodStart];
NSLog(@"executionTime = %f", executionTime);

Swift:

let methodStart = NSDate()

/* ... Do whatever you need to do ... */

let methodFinish = NSDate()
let executionTime = methodFinish.timeIntervalSinceDate(methodStart)
print("Execution time: \(executionTime)")

Swift3:

let methodStart = Date()

/* ... Do whatever you need to do ... */

let methodFinish = Date()
let executionTime = methodFinish.timeIntervalSince(methodStart)
print("Execution time: \(executionTime)")

Easy to use and has sub-millisecond precision.

How do I time a method's execution in Java?

There is always the old-fashioned way:

long startTime = System.nanoTime();
methodToTime();
long endTime = System.nanoTime();

long duration = (endTime - startTime); //divide by 1000000 to get milliseconds.

How to measure time taken by a function to execute

Using performance.now():

var startTime = performance.now()

doSomething() // <---- measured code goes between startTime and endTime

var endTime = performance.now()

console.log(`Call to doSomething took ${endTime - startTime} milliseconds`)

In Node.js it is required to import the performance class

importing performance

const { performance } = require('perf_hooks');


Using console.time: (living standard)

console.time('doSomething')

doSomething() // <---- The function you're measuring time for

console.timeEnd('doSomething')

Note:
The string being passed to the time() and timeEnd() methods must match
(for the timer to finish as expected).

console.time() documentations:

  • MDN documentation
  • Node.js documentation

Logging of method execution time

If you want to make the code look less ugly:

Change

def startTime
LOGGER.isDebugEnabled() {
startTime = System.currentTimeMillis()
}

to

def startTime = System.currentTimeMillis()

I am not a fan of isDebugEnabled for these one liners. You will not see any performance difference without it.

Calculate the execution time of a method

Stopwatch is designed for this purpose and is one of the best ways to measure time execution in .NET.

var watch = System.Diagnostics.Stopwatch.StartNew();
// the code that you want to measure comes here
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;

Do not use DateTime to measure time execution in .NET.


UPDATE:

As pointed out by @series0ne in the comments section: If you want a real precise measurement of the execution of some code, you will have to use the performance counters that's built into the operating system. The following answer contains a nice overview.

Measuring code execution time

A better way would be to use Stopwatch, instead of DateTime differences.

Stopwatch Class - Microsoft Docs

Provides a set of methods and properties that you can use to
accurately measure elapsed time.

// create and start a Stopwatch instance
Stopwatch stopwatch = Stopwatch.StartNew();

// replace with your sample code:
System.Threading.Thread.Sleep(500);

stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);

Rudimentary ways to measure execution time of a method

Actually, +[NSDate timeIntervalSinceReferenceDate] returns an NSTimeInterval, which is a typedef for a double. The docs say

NSTimeInterval is always specified in seconds; it yields sub-millisecond precision over a range of 10,000 years.

So it's safe to use for millisecond-precision timing. I do so all the time.

Best way to measure the execution time of methods

One way to do this would be to use an assembly weaver like 'Fody' with an extension that does exactly what you are looking for. Please see this link for an example extension: https://github.com/Fody/MethodTimer

How Fody works is it injects code into your code-base at compile time, utilising attributes as you have suggested in your question. The provided extension does just as you have described using a stopwatch to log the execution time of your code.

An example of usage:

Once the library is installed, you can add the annotation [Time] to the methods you wish to measure:

[Time]
public void TestMethod()
{
//code here
}

You can then create a custom interceptor (A static class that will be automatically picked up by the Fody extension) which you can use to add a metric track into application insights:

public static class MethodTimeLogger
{
public static void Log(MethodBase methodBase, long milliseconds)
{
var sample = new MetricTelemetry();
sample.Name = methodBase.Name;
sample.Value = milliseconds;
// Your telemetryClient here
telemetryClient.TrackMetric(sample);
}
}

Find how long it takes a function to execute in seconds

Try this:

let start = Date.timeIntervalSinceReferenceDate

// do stuff

let end = Date.timeIntervalSinceReferenceDate
let secondsElapsed = end - start

secondsElapsed will be a Double, but it will be in seconds. You can round it or truncate it if you want an Int.

Hope this helps!

Measuring execution time of a function in C++

It is a very easy-to-use method in C++11. You have to use std::chrono::high_resolution_clock from header.

Use it like so:

#include 

/* Only needed for the sake of this example. */
#include
#include

void long_operation()
{
/* Simulating a long, heavy operation. */

using namespace std::chrono_literals;
std::this_thread::sleep_for(150ms);
}

int main()
{
using std::chrono::high_resolution_clock;
using std::chrono::duration_cast;
using std::chrono::duration;
using std::chrono::milliseconds;

auto t1 = high_resolution_clock::now();
long_operation();
auto t2 = high_resolution_clock::now();

/* Getting number of milliseconds as an integer. */
auto ms_int = duration_cast(t2 - t1);

/* Getting number of milliseconds as a double. */
duration ms_double = t2 - t1;

std::cout << ms_int.count() << "ms\n";
std::cout << ms_double.count() << "ms\n";
return 0;
}

This will measure the duration of the function long_operation.

Possible output:

150ms
150.068ms

Working example: https://godbolt.org/z/oe5cMd



Related Topics



Leave a reply



Submit