How Can I Determine How Long It Takes a Script to Run?

Hey, Scripting Guy! Question

Hey, Scripting Guy! Is there a good way to time how long it takes for a script to run?

— BN, Montreal, Canada

SpacerHey, Scripting Guy! AnswerScript Center

Hey, BN. Probably the easiest way to do this is to let the script time itself. To accomplish that feat, set the first line of the script to this:

dtmStart = Now

This code simply sets the value of the variable dtmStart to the current date and time. Now, make the last two lines of the script look like this:

dtmEnd = Now
Wscript.Echo DateDiff("s", dtmStart, dtmEnd)

What does that do for us? Well, now we’ve saved the time the script began and the time the script ended. To determine how long it took for the script to run, we just need to subtract the beginning time from the ending time. For example, if the script started at 8:40 and finished at 8:41, we’d calculate the running time like this:

8:41 - 8:40 = 60 seconds

Fortunately that kind of date arithmetic is very easy in VBScript. All we have to do is call the DateDiff function, and pass along three values:

The time interval we want our answer to be in.

For this script, we want to measure running time in seconds, so we pass the value “s”. For longer scripts, we might pass the value “m” in order to get the time in minutes.

The time the script began.

This is stored in the variable dtmStart.

The time the script ended.

This is tored in the variable dtmEnd.

The entire script might look like this. Note that for demonstration purposes we’ve included code that simply loops from 1 to 10,000,000 without doing anything else; that’s there simply to waste some time and make the script run a bit longer.

dtmStart = Now()

For i = 1 to 10000000

dtmEnd = Now()
Wscript.Echo DateDiff("s", dtmStart, dtmEnd)

In case you’re wondering, you can only measure running times to the nearest second; you can’t calculate times in microseconds or milliseconds or anything crazy like that. That might sound like a limitation, but look at it this way: if your script can complete in less than a second then you really don’t have much to worry about, do you?

For more information about the DateDiff function, see this portion of the Microsoft Windows 2000 Scripting Guide.

Comments (1)

  1. says:

    MsgBox(DateDiff("s", start_time, end_time)) always gives the same answer of


    What am I doing wrong??

Skip to main content