问题描述
我正在尝试从运行Angstrom Linux发行版的Beagle Bone中的ADC读取数据.我需要使用类似sleep()
的延迟机制,以便仅在特定时间读取样本,以帮助符合特定的采样率. 我还需要计算执行时间.
I am trying to read data from the ADC in the Beagle Bone, running Angstrom Linux distribution. I need to use a delay mechanism like sleep()
, to only read samples at specific time, to help conform to a specific sample rate. I also am required to calculate the execution time.
以下是示例POC(概念验证),以演示我面临的问题:
Here is a sample POC (proof of concept), to demonstrate the problem I am facing:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
clock_t begin, end;
while(1)
{
begin = clock();
sleep(1); // delay for 1 sec
end = clock();
printf("Execution time = %f\n",((float)(end-begin)/CLOCKS_PER_SEC));
}
}
我总是以0.000000
作为执行时间.
I always get the execution time as 0.000000
.
为什么我没有得到1.000000
秒的结果?我的猜测是调用sleep()
将抢占我的程序,但我不确定.
Why do I not get my result as 1.000000
seconds? My guess is calling sleep()
will pre-empt my program, but I am not sure.
我还需要什么其他选项来计算经过的执行时间(包括延迟)?
What other option do I have to calculate elapsed execution time which includes a delay?
推荐答案
计算执行时间的解决方案是在程序的开头和结尾获取时间戳.然后有所作为.
The solution to calculate execution time is to get the timestamp at the beginning of your program and at the end. Then make the difference.
#include <stdio.h>
#include <time.h>
int main() {
time_t begin;
time(&begin);
// Somethings
time_t end;
time(&end);
printf("Execution time %f\n", difftime(end, begin));
return (0);
}
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
int main() {
struct timeval tv;
gettimeofday(&tv, NULL);
double begin =
(tv.tv_sec) * 1000 + (tv.tv_usec) / 1000 ;
sleep(2);
gettimeofday(&tv, NULL);
double end =
(tv.tv_sec) * 1000 + (tv.tv_usec) / 1000 ;
printf("Execution time %f\n", end - begin);
return (0);
}
这篇关于使用sleep()时计算执行时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!