gpt4 book ai didi

c++ - Linux C++ : "Holes" in time sampling

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

我有一个运行 while(1) 循环的线程。在那个循环中,我不断检查时间,因为我需要在特定时间执行特定任务。但是,当我将时间打印到屏幕上时,我发现每隔几秒就会出现一个将近 700 毫秒的“空洞”。我尝试设置进程优先级:

 policy =  SCHED_FIFO;
param.sched_priority = 18;
if( sched_setscheduler( id, policy, &param ) == -1 )
{
printf("Error setting scheduler/priority!\n");
}

以及线程优先级:

pthread_attr_t attr;
struct sched_param param;
pthread_attr_init(&attr);
pthread_attr_setschedpolicy(&attr, SCHED_RR);
param.sched_priority = 50;
pthread_attr_setschedparam(&attr, &param);
m_INVThreadID = pthread_create( &m_BaseStationLocatorsThread, &attr,
ThreadBaseStationLocatorsHandler, (void*)
(this));//Linux

但这并没有帮助。

我得到时间的方式是:

 struct timespec start;


clock_gettime( CLOCK_MONOTONIC_RAW, &start);
//gettimeofday(&tim, NULL);
//wInitTime = tim.tv_sec*1000 + tim.tv_usec/1000.0;
double x = start.tv_sec;
double y = start.tv_nsec;
x=x*1000;
y = y/1000000;
double result = x+ y;
return result;

或者:

STime   TimeHandler::GetTime()
{
STime tmpt;
time_t rawtime;
tm * timeinfo;
time(&rawtime);
timeinfo=localtime(&rawtime);
tmpt.day_of_month = timeinfo->tm_mday;
tmpt.month = timeinfo->tm_mon+1;
tmpt.year = timeinfo->tm_year+1900;
tmpt.Hours = timeinfo->tm_hour;
tmpt.Min = timeinfo->tm_min;
tmpt.Sec = timeinfo->tm_sec;
tmpt.MilliSeconds = GetCurrentTimeMilliSeconds();
return tmpt;
}

现在打印时间:

STime timeinfo = GetTime();
string curTime;
int datePart;
string datePartSTR;
std::ostringstream convert;

datePart =timeinfo.day_of_month;
convert << datePart;
//curTime.append( convert.str());
convert << "/";
datePart = timeinfo.month;
convert << datePart;
//curTime.append( convert.str());
convert << "/";
datePart =timeinfo.year;
convert << datePart;
//curTime.append( convert.str());

convert << " ";
datePart =timeinfo.Hours;
if (timeinfo.Hours<10)
convert <<0;
convert << datePart;
//curTime.append( convert.str());
convert << ":";
datePart =timeinfo.Min;
if (timeinfo.Min<10)
convert <<0;
convert << datePart;
//curTime.append( convert.str());
convert << ":";
datePart =timeinfo.Sec;
if (timeinfo.Sec<10)
convert <<0;
convert << datePart;
convert << ":";
datePart =timeinfo.MilliSeconds;
if (timeinfo.MilliSeconds<100)
convert << 0;
if (timeinfo.MilliSeconds<10)
convert << 0;
convert << datePart;
curTime.append( convert.str());


return curTime;

有什么想法吗?

谢谢!

最佳答案

首先,最好使用 Cron 进行作业调度,而不是在循环中手动等待必要的时刻,然后手动启 Action 业。

根据“时间漏洞”:正如 jdv-Jan de Vaan 在评论中所说,Linux 不是实时操作系统(以及 Windows 和大多数其他面向消费者的操作系统)。鉴于此,您永远无法确定您的线程将在预期的时间片内以毫秒为精度处于事件状态。操作系统调度程序、系统事件,甚至 CPU 节流/节能都可能导致您的应用休眠时间超过几毫秒。因此,最好考虑一些阈值间隔而不是固定时间。

关于c++ - Linux C++ : "Holes" in time sampling,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18738680/

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