gpt4 book ai didi

clock_gettime 总是显示 0

转载 作者:太空宇宙 更新时间:2023-11-04 02:55:52 24 4
gpt4 key购买 nike

我想用 clock_gettime 测量挂钟时间,但每次运行我的代码时,它都显示 0。这是为什么? (我希望我的结果以毫秒为单位。)

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>

int main( int argc, char **argv )
{
struct timespec start, stop;
unsigned long accum;

if( clock_gettime( CLOCK_REALTIME, &start) == -1 ) {
perror( "clock gettime" );
exit( EXIT_FAILURE );
}

int i;
for(i=0; i<100000000; i++){int a = 3; int b = 100; int c = a*b;}

//system( argv[1] );

if( clock_gettime( CLOCK_REALTIME, &stop) == -1 ) {
perror( "clock gettime" );
exit( EXIT_FAILURE );
}

accum = (unsigned long)( (stop.tv_sec - start.tv_sec) * 1000) + (unsigned long)( (stop.tv_nsec - start.tv_nsec) / 1000000 ) +0.5;
printf( "%lu\n", accum );
return( EXIT_SUCCESS );
}

最佳答案

因为编译器优化了你的循环。在循环内做一些不容易简化的事情(通过编译器);所以创造一些结果。然后在循环后使用(例如打印)这个结果。

您也可以尝试在编译时关闭优化。但由于您的当前循环很容易优化,因此这可能不会有什么不同。

关于clock_gettime 总是显示 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17453383/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com