如何衡量使用ANSI C毫秒的时间? [英] How to measure time in milliseconds using ANSI C?
问题描述
仅使用ANSI C,有没有什么办法来衡量时间毫秒precision或更多?我在浏览time.h中,但我只找到第二个precision功能。
Using only ANSI C, is there any way to measure time with milliseconds precision or more? I was browsing time.h but I only found second precision functions.
推荐答案
有没有ANSI C的功能,提供了超过1秒的时间分辨率更好,但在POSIX功能<一个href=\"http://www.opengroup.org/onlinepubs/000095399/functions/gettimeofday.html\"><$c$c>gettimeofday$c$c>提供微秒级分辨率。时钟功能只测量的时间量的方法已经使用了执行和不准确在许多系统
There is no ANSI C function that provides better than 1 second time resolution but the POSIX function gettimeofday
provides microsecond resolution. The clock function only measures the amount of time that a process has spent executing and is not accurate on many systems.
您可以使用此功能是这样的:
You can use this function like this:
struct timeval tval_before, tval_after, tval_result;
gettimeofday(&tval_before, NULL);
// Some code you want to time, for example:
sleep(1);
gettimeofday(&tval_after, NULL);
timersub(&tval_after, &tval_before, &tval_result);
printf("Time elapsed: %ld.%06ld\n", (long int)tval_result.tv_sec, (long int)tval_result.tv_usec);
这将返回经过时间:1.000870
我的机器上
这篇关于如何衡量使用ANSI C毫秒的时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!