Skip to content

Instantly share code, notes, and snippets.

@kana-ph
Last active January 19, 2017 13:16
Show Gist options
  • Save kana-ph/c325a76a81e7061a67150e59ed3a6dbd to your computer and use it in GitHub Desktop.
Save kana-ph/c325a76a81e7061a67150e59ed3a6dbd to your computer and use it in GitHub Desktop.
Utility class/functions for measuring code execution time.

C

#include <stdio.h>
#include "stopwatch.h"

int main() {
	double elapsed_seconds;
	stopwatch_t stopwatch;
	
	stopwatch = start_timer();
	do_something();
	elapsed_seconds = end_timer(stopwatch);
	
	printf("Elapsed time: %f seconds\n", elapsed_seconds);
	return 0;
}

C#

public class MyApp
{
	public static void Main(string[] args)
	{
		TimedAction.Run(() => {
			doSomething();
		});
	}
}

Groovy

TimedAction.run {
	doSomething()
}

Java (No Lambda)

public class MyApp {
	public static void main(String[] args) {
		TimedAction.run(new Runnable() {
			@Override
			public void run() {
				doSomething();
			}
		});
	}
}

Java (With Lambda)

public class MyApp {
	public static void main(String[] args) {
		TimedAction.run(() -> doSomething());
	}
}

Python

runWithTimer(doSomething)
#include <time.h>
#include <stdlib.h>
typedef struct {
clock_t start;
clock_t end;
} stopwatch_t;
stopwatch_t *start_timer() {
stopwatch_t *timer = (stopwatch_t *)malloc(sizeof(stopwatch_t *));
timer->start = clock();
return timer;
}
double end_timer(stopwatch_t *timer) {
double elapsed_seconds;
timer->end = clock();
elapsed_seconds = (double)(timer->end - timer->start) / CLOCKS_PER_SEC;
free(timer);
return elapsed_seconds;
}
using System.Diagnostics;
public sealed class TimedAction
{
private TimedAction() { }
public delegate void Action();
public static long Run(Action action)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
action();
stopwatch.Stop();
return stopwatch.ElapsedMilliseconds;
}
}
final class TimedAction {
private TimedAction() {}
static long run(Closure action) {
long start = System.nanoTime()
action()
long end = System.nanoTime()
long elapsedNanoSeconds = end - start
return elapsedNanoSeconds
}
}
public final class TimedAction {
private TimedAction() {}
public static long run(Runnable action) {
long start = System.nanoTime();
action.run();
long end = System.nanoTime();
long elapsedNanoSeconds = end - start;
return elapsedNanoSeconds;
}
}
import time
def runWithTimer(runnable):
start = time.time()
runnable()
end = time.time()
return end-start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment