次并且 CLOCK_PER_SEC 计算出错误的时间
times and CLOCK_PER_SEC calculates the wrong time
我对这个程序有疑问:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include <sys/times.h>
clock_t start_time;
clock_t get_user_ticks()
{
struct tms t;
times(&t);
return t.tms_utime;
}
void start_stopwatch()
{
start_time = get_user_ticks();
}
void stop_stopwatch()
{
clock_t stop_time = get_user_ticks();
double ticks = stop_time - start_time;
double s = ticks / CLOCKS_PER_SEC;
printf("elapsed time: %fs\n", s);
}
int main(int argc, char** argv)
{
start_stopwatch();
int sum = 0;
for (long i = 0; i < 1000000000; i++) {
sum += i;
}
printf("sum: %i\n", sum);
stop_stopwatch();
return 0;
}
当我像这样编译和执行它时:gcc -O0 test.c ; time ./a.out
我得到以下输出:
sum: -1243309312
elapsed time: 0.000250s
real 0m2.509s
user 0m2.508s
sys 0m0.000s
为什么我的程序输出错了 10000 倍?我怎样才能像 time
命令那样获得更高的精度?
在 Debian Buster 上测试,64 位,gcc 版本 8.3.0。
嗯,因为这里用错了CLOCKS_PER_SEC
。 CLOCKS_PER_SEC
是将clock()
的return值转换为秒。但是...请注意 posix times docs:
Applications should use sysconf(_SC_CLK_TCK) to determine the number of clock ticks per second as it may vary from system to system.
man 2 times 在 NOTES
部分也提到了这一点。
做:
double s = ticks / sysconf(_SC_CLK_TCK);
And how can I get higher precision as with the time command?
使用getrusage
。另见 bash sources of time command.
我对这个程序有疑问:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include <sys/times.h>
clock_t start_time;
clock_t get_user_ticks()
{
struct tms t;
times(&t);
return t.tms_utime;
}
void start_stopwatch()
{
start_time = get_user_ticks();
}
void stop_stopwatch()
{
clock_t stop_time = get_user_ticks();
double ticks = stop_time - start_time;
double s = ticks / CLOCKS_PER_SEC;
printf("elapsed time: %fs\n", s);
}
int main(int argc, char** argv)
{
start_stopwatch();
int sum = 0;
for (long i = 0; i < 1000000000; i++) {
sum += i;
}
printf("sum: %i\n", sum);
stop_stopwatch();
return 0;
}
当我像这样编译和执行它时:gcc -O0 test.c ; time ./a.out
我得到以下输出:
sum: -1243309312
elapsed time: 0.000250s
real 0m2.509s
user 0m2.508s
sys 0m0.000s
为什么我的程序输出错了 10000 倍?我怎样才能像 time
命令那样获得更高的精度?
在 Debian Buster 上测试,64 位,gcc 版本 8.3.0。
嗯,因为这里用错了CLOCKS_PER_SEC
。 CLOCKS_PER_SEC
是将clock()
的return值转换为秒。但是...请注意 posix times docs:
Applications should use sysconf(_SC_CLK_TCK) to determine the number of clock ticks per second as it may vary from system to system.
man 2 times 在 NOTES
部分也提到了这一点。
做:
double s = ticks / sysconf(_SC_CLK_TCK);
And how can I get higher precision as with the time command?
使用getrusage
。另见 bash sources of time command.