sna*_*ile 41 c windows time winapi
我想知道一些代码块执行了多长时间.像这样的东西:
startStopwatch();
// do some calculations
stopStopwatch();
printf("%lf", timeMesuredInSeconds);
Run Code Online (Sandbox Code Playgroud)
怎么样?
KLe*_*ee1 64
您可以clock在time.h中使用该方法
例:
clock_t start = clock();
/*Do something*/
clock_t end = clock();
float seconds = (float)(end - start) / CLOCKS_PER_SEC;
Run Code Online (Sandbox Code Playgroud)
Ste*_*hen 18
您可以使用time.h库,特别是time和difftime函数:
/* difftime example */
#include <stdio.h>
#include <time.h>
int main ()
{
time_t start,end;
double dif;
time (&start);
// Do some calculation.
time (&end);
dif = difftime (end,start);
printf ("Your calculations took %.2lf seconds to run.\n", dif );
return 0;
}
Run Code Online (Sandbox Code Playgroud)
(示例改编自上面链接的difftime网页.)
请注意,这种方法只能给予值得准确的秒- time_t自记录秒UNIX纪元(1970年1月1日).
有时需要测量天文时间而不是CPU 时间(尤其适用于Linux):
#include <time.h>
double what_time_is_it()
{
struct timespec now;
clock_gettime(CLOCK_REALTIME, &now);
return now.tv_sec + now.tv_nsec*1e-9;
}
int main() {
double time = what_time_is_it();
printf("time taken %.6lf\n", what_time_is_it() - time);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
标准 C 库提供了该time函数,如果您只需要比较秒,则该函数非常有用。不过,如果您需要毫秒精度,最便携的方法是调用timespec_get. 如果系统支持的话,它可以报出高达纳秒精度的时间。然而,调用它需要花费更多的精力,因为它涉及一个结构。下面的函数仅将结构转换为简单的 64 位整数。
#include <stdio.h>
#include <inttypes.h>
#include <time.h>
int64_t millis()
{
struct timespec now;
timespec_get(&now, TIME_UTC);
return ((int64_t) now.tv_sec) * 1000 + ((int64_t) now.tv_nsec) / 1000000;
}
int main(void)
{
printf("Unix timestamp with millisecond precision: %" PRId64 "\n", millis());
}
Run Code Online (Sandbox Code Playgroud)
与 不同的是clock,此函数返回一个 Unix 时间戳,因此它将正确计算阻塞函数(例如 )所花费的时间sleep。对于基准测试和实现考虑运行时间的延迟来说,这是一个有用的属性。