How to Measure Milliseconds in ANSI C
The American National Standards Institute (ANSI) provides standardized coding guidelines that enhances software portability, but in doing so some of the more robust features of the C language are lost. Producing a perfect determination of time to the millisecond is never easy (due to the nature of digital computing); developing a solution using strict ANSI C standards is impossible. However, a savvy ANSI C programmer can make use of the clock() function and simple math to calculate the time to the precision of milliseconds.
Instructions
-
-
1
Open a plain text editor (such as Notepad). Copy the code below and save your file.
#include <time.h>
double elapsed; // in milliseconds
clock_t start, end;
start = clock();
/* do some work */
end = clock();
elapsed = ((double) (end - start) * 1000) / CLOCKS_PER_SEC;
-
2
Compile your code. If there are any errors, debug, correct and compile again.
-
-
3
When your compiler produces a return code of zero, execute your program by double clicking the newly produced EXE file through Explorer or by running the executable via the command line.
-
1
Tips & Warnings
If you don't have a compiler, one suggestion is to use GCC (Gnu Compiler Collection). It's free, easy to use and supported and developed under open source.
Save your file with an extension of c (such as millisecond.c). Most compilers won't work without the appropriate extension.
Many compilers require an input parameter to compile a program to ANSI standards. Check the documentation of your compiler program for further details.
References
Resources
- Photo Credit digital clock image by JoLin from Fotolia.com