每"x"秒从C++程序中提取变量的值

Extract a variable's value from a C++ program every 'x' seconds

本文关键字:提取 变量 程序 秒从 C++      更新时间:2023-10-16

如何在每'x'秒中执行此操作?我有一个客户端服务器回声程序,我需要在图中的每一秒钟绘制吞吐量。该程序是使用Ubuntu 14.04中的g++编译的。我想从外部观察此程序,并每x秒输出文件中的值。客户端的源代码,我需要在每个1秒获得吞吐量:

while(interval > 0){
  for(int i = 0;i < no_of_packets;i++){
    currentTime(buffer_rcvd);
    bytes_sent = sendto(socket_id, buffer_rcvd, sizeof(buffer_rcvd), 0, (struct sockaddr *) &server_addr, addr_size);
    buffer_rcvd[bytes_sent] = '';
    bytes_rcvd = recvfrom(socket_id, buffer_rcvd, sizeof(buffer_rcvd), 0, (struct sockaddr *) &server_addr, &addr_size);
    cout << "Received message on trip " << trip << " : " << buffer_rcvd << endl;
  }
  no_of_packets++, trip++;
  sleep(interval--);
}

答案取决于您所需的准确性,平台等。这里有一些建议:

Chrono

将其放在代码中经常执行的某个位置。但是,这仅在使用C 11(或更高版本)时才起作用。你应该!

using namespace std::chrono;
/* Put this outside of your function or loop */
auto lastOutputTime = steady_clock::now();
/* Put this inside of your function or loop */
auto now = steady_clock::now();
if (now - lastOutputTime >= 60s) {
  auto throughput = getCurrentThroughput();
  std::cout << "Throughput: " << throughput << std::endl;
  lastOutputTime = now;          
}

时钟()

另一个甚至可以在C中起作用的选项(除输出本身外)。但是,正如@some程序员所指出的那样,该方法取决于平台。通常,您可以使用此时间来测量CPU时间,而不是墙壁锁定时间。因此,它可能对您而言可能不够准确。

/* Put this outside of your function or loop */
clock_t lastOutputTime = 0;
clock_t now = clock();
/* Put this inside of your function or loop */
if(now - lastOutputTime > CLOCKS_PER_SEC*60) {
  double throughput = getCurrentThroughput();
  std::cout << "Throughput: " << throughput << std::endl;
  lastOutputTime = now;
}

用于使用clock(),您必须将以下内容添加到标题

#include <ctime>

time()

如果您需要墙壁锁定时间,而C 11不可用,则可以使用time()。但是,它仅提供一秒钟的精度,这可能对您而言可能不足。

/* Put this outside of your function or loop */
time_t lastOutputTime;
time(&lastOutputTime);
/* Put this inside of your function or loop */
time_t now;
time(&now);
if(difftime(now,lastOutputTime) >= 60) {
  double throughput = getCurrentThoughput();
  std::cout << "Throughput: " << throughput << std::endl;
  lastOutputTime = now;
}

您的问题真的不清楚。

这是一些想法。

如果您正在编码程序并可以修改其源代码,则可以在仪器目的中添加一些服务器功能。例如,您可以添加一些HTTP服务器功能:您将使用一些HTTP服务器库,例如Libonion,例如,您可以使用。改进您的代码,使其在http://localhost:4567/status URL上使用,并作为对每个GET http://localhost:4567/status HTTP请求的HTTP响应提供一些带有适当状态变量的JSON内容。顺便说一句,这是我建议做什么。

您还可以使用所有调试选项(例如,使用g++ -g -O编译)编译程序,并使用一些巧妙的脚本,这些脚本将:使用Sigstop信号停止该过程,启动一些gdb -p命令,使用backtraceprint GDB命令,然后继续继续Sigcont

的过程

您也可以考虑PROC(5)。也许巧妙地使用Strace(1)就足够了。

您可以将重要变量放入共享内存段(使用指针和某些公共struct,代码一个从该共享内存段中读取的实用程序)。读取SHM_OVERVIEW(7)(以及Sem_overview(7)以进行同步)。

您可能会想到其他过程间通信。参见插座(7),管道(7),FIFO(7)和读取高级Linux编程。

您可以启动一个额外的(仪器)线程,该线程将登录到某些文件等...

另请参见时间(7)&amp;信号(7)

也许您的程序应该具有适当的事件循环(请参见Poll(2)...)。

否则,您的任务是不可能的:在运行时,C 变量不再存在(它们在寄存器中或在存储位置中)。

因此,取决于您真正想做的事情,这可能是容易或不可能的。