How to Measure Elapsed Time

Measuring elapsed time with the Time module

start_time = time.time()
# your code
elapsed_time = time.time() - start_time

You can also write simple decorator to simplify measurement of execution time of various functions:

import time
from functools import wraps

PROF_DATA = {}

def profile(fn):
@wraps(fn)
def with_profiling(*args, **kwargs):
start_time = time.time()

ret = fn(*args, **kwargs)

elapsed_time = time.time() - start_time

if fn.__name__ not in PROF_DATA:
PROF_DATA[fn.__name__] = [0, []]
PROF_DATA[fn.__name__][0] += 1
PROF_DATA[fn.__name__][1].append(elapsed_time)

return ret

return with_profiling

def print_prof_data():
for fname, data in PROF_DATA.items():
max_time = max(data[1])
avg_time = sum(data[1]) / len(data[1])
print "Function %s called %d times. " % (fname, data[0]),
print 'Execution time max: %.3f, average: %.3f' % (max_time, avg_time)

def clear_prof_data():
global PROF_DATA
PROF_DATA = {}

Usage:

@profile
def your_function(...):
...

You can profile more then one function simultaneously. Then to print measurements just call the print_prof_data():

How to measure elapsed time

When the game starts:

long tStart = System.currentTimeMillis();

When the game ends:

long tEnd = System.currentTimeMillis();
long tDelta = tEnd - tStart;
double elapsedSeconds = tDelta / 1000.0;

How do I measure time elapsed in Java?

Unfortunately, none of the ten answers posted so far are quite right.

If you are measuring elapsed time, and you want it to be correct, you must use System.nanoTime(). You cannot use System.currentTimeMillis(), unless you don't mind your result being wrong.

The purpose of nanoTime is to measure elapsed time, and the purpose of currentTimeMillis is to measure wall-clock time. You can't use the one for the other purpose. The reason is that no computer's clock is perfect; it always drifts and occasionally needs to be corrected. This correction might either happen manually, or in the case of most machines, there's a process that runs and continually issues small corrections to the system clock ("wall clock"). These tend to happen often. Another such correction happens whenever there is a leap second.

Since nanoTime's purpose is to measure elapsed time, it is unaffected by any of these small corrections. It is what you want to use. Any timings currently underway with currentTimeMillis will be off -- possibly even negative.

You may say, "this doesn't sound like it would ever really matter that much," to which I say, maybe not, but overall, isn't correct code just better than incorrect code? Besides, nanoTime is shorter to type anyway.

Previously posted disclaimers about nanoTime usually having only microsecond precision are valid. Also it can take more than a whole microsecond to invoke, depending on circumstances (as can the other one), so don't expect to time very very small intervals correctly.

How to measure time elapsed on Javascript?

The Date documentation states that :

The JavaScript date is based on a time value that is milliseconds
since midnight January 1, 1970, UTC

Click on start button then on end button. It will show you the number of seconds between the 2 clicks.

The milliseconds diff is in variable timeDiff. Play with it to find seconds/minutes/hours/ or what you need

var startTime, endTime;
function start() { startTime = new Date();};
function end() { endTime = new Date(); var timeDiff = endTime - startTime; //in ms // strip the ms timeDiff /= 1000;
// get seconds var seconds = Math.round(timeDiff); console.log(seconds + " seconds");}
<button onclick="start()">Start</button>
<button onclick="end()">End</button>

Measure elapsed time in C?

The C Standard does not define a portable way to do this. The time() library function has a definition of 1 second, which is inappropriate for your purpose. As mentioned by @Puck, C11 did introduce timespec_get() to retrieve a more precise time value, but this function is not widely supported and may not provide the expected accuracy.

Other functions are available on selected systems:

  • The POSIX standard defines gettimeofday() and clock_gettime() which can return precise real time with the argument CLOCK_REALTIME.

  • OS/X has a more precise alternative: clock_gettime_nsec_np which returns a 64-bit value in nanosecond increments.

  • Microsoft documents this for Windows.

Note however that performing precise and reliable sub-microsecond benchmarks is a difficult game to say the least.

Why are there a big difference when measuring elapsed time according to where to measure?

Taking a snapshot of the time before std::cin >> a >> b; leads to an inaccurate measurement as you're likely starting the clock before you type in the values for a and b. Generally you want to put your timing as close as possible to the thing you're actually measuring.

Measure elapsed time from fixed datetime

You can import the datetime module, which has a class with the same name, with method datetime.datetime.now().

This returns an object representing the time when it is called.

This object has the method replace(), which can be used to 'change' the time to 8:30, if you call it like so - replace(hour=8, minute=30).

You can then create another similar object but without replacing the time, then you can simply subtract the first from the second to get the elapsed time as a datetime object.

This will then have elapsed_time.seconds to give you the time change in seconds, which can be divided by 60 if you want for the time in minutes.

Example

import datetime

time_A = datetime.datetime.now()
time_A = time_A.replace(hour=8, minute=30)

time_B = datetime.datetime.now()

elapsed_time = time_B - time_A

print(elapsed_time.seconds, "seconds have passed since 8:30 this morning")

If you wanted this for a specific timezone, you can add or subtract the offset from your current timezone. So if you are for example, 5 hours ahead of CST, you can have it get the difference from 3:30 instead.



Related Topics



Leave a reply



Submit