c - sprintf 是做什么的?(原:OpenGL 中的 FPS 计算)



对于FPS计算,我使用了一些在网上找到的代码,它运行良好。但是,我真的不明白。这是我使用的功能:

void computeFPS()
{
  numberOfFramesSinceLastComputation++;
  currentTime = glutGet(GLUT_ELAPSED_TIME);
  if(currentTime - timeSinceLastFPSComputation > 1000)
  {
    char fps[256];
    sprintf(fps, "FPS: %.2f", numberOfFramesSinceLastFPSComputation * 1000.0 / (currentTime . timeSinceLastFPSComputation));
    glutSetWindowTitle(fps);
    timeSinceLastFPSComputation = currentTime;
    numberOfFramesSinceLastComputation = 0;
  }
 }

我的问题是,冲刺调用中计算的值如何存储在 fps 数组中,因为我并没有真正分配它。

这不是关于OpenGL的问题,而是C标准库的问题。阅读 s(n)printf 的参考文档会有所帮助:

man s(n)printf: http://linux.die.net/man/3/sprintf

简而言之,snprintf 获取指向用户提供的缓冲区和格式字符串的指针,并根据格式字符串和附加参数中给出的值填充缓冲区。


我的建议是:如果你必须问这样的事情,就不要处理OpenGL。在提供缓冲区对象数据和着色器源时,您需要熟练地使用指针和缓冲区。如果你打算使用C来做到这一点,请先买一本关于C的书,并彻底学习它。与C++不同的是,你实际上可以在几个月内在一定程度上学习C。

这个函数应该在每次重绘主循环时调用(对于每一帧)。因此,它所做的是增加帧计数器并获取该帧显示的当前时间。每秒一次(1000毫秒),它会检查该计数器并将其重置为0。因此,当每秒获取计数器值时,它会获取其值并将其显示为窗口的标题。

/**
 * This function has to be called at every frame redraw.
 * It will update the window title once per second (or more) with the fps value.
 */
void computeFPS()
{
  //increase the number of frames
  numberOfFramesSinceLastComputation++;
  //get the current time in order to check if it has been one second
  currentTime = glutGet(GLUT_ELAPSED_TIME);
  //the code in this if will be executed just once per second (1000ms)
  if(currentTime - timeSinceLastFPSComputation > 1000)
  {
    //create a char string with the integer value of numberOfFramesSinceLastComputation and assign it to fps
    char fps[256];
    sprintf(fps, "FPS: %.2f", numberOfFramesSinceLastFPSComputation * 1000.0 / (currentTime . timeSinceLastFPSComputation));
    //use fps to set the window title
    glutSetWindowTitle(fps);
    //saves the current time in order to know when the next second will occur
    timeSinceLastFPSComputation = currentTime;
    //resets the number of frames per second.
    numberOfFramesSinceLastComputation = 0;
  }
 }

最新更新