我有一个递增的整数值,并想找到该整数的每秒平均值。我知道除非您执行特定且复杂的操作,否则 C 中不存在计时器 [我是 C 新手] 有没有更简单的方法可以做到这一点?最好在进行计算时重置该值,以免内存中存在如此大的数字,因为该应用程序将运行很长时间。
2 回答
I think you will want to include time.h
, and use some of its functions and structs (this is actually not a bad way of learning the basics of C). There is an explanation and a few examples here.
If you need sub-second accuracy I suggest you use clock_gettime()
, which will give you nanosecond resolution.
Here is an example:
#include <stdio.h>
#include <time.h>
struct timespec diff(struct timespec start, struct timespec end);
int main()
{
struct timespec time1, time2, timeDiff;
int temp, i;
// Get the start time
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
// Do some work
for (i = 0; i< 242000000; i++)
temp+=temp;
// Get the end time
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time2);
// Calculate the difference
timeDiff = diff(time1,time2);
printf("%d.%d\n", timeDiff.tv_sec, timeDiff.tv_nsec);
return 0;
}
struct timespec diff(struct timespec start, struct timespec end)
{
struct timespec temp;
if ((end.tv_nsec-start.tv_nsec)<0) {
temp.tv_sec = end.tv_sec-start.tv_sec-1;
temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
} else {
temp.tv_sec = end.tv_sec-start.tv_sec;
temp.tv_nsec = end.tv_nsec-start.tv_nsec;
}
return temp;
}
You will need to compile with something like:
gcc -o timetest timetest.c -lrt
The -lrt
part of the command tells the C linker to link to the Realtime library, which contains the definition of clock_gettime()
.
您可以只使用gettimeofday()
来获取时间值。您需要存储一个这样的读数,以便您可以将最近的读数与旧的读数进行比较,并计算出它们之间的时间。如果您以秒为单位执行此操作,则可以将整数除以该间隔并获得每秒的平均值。