Function to calculate how often users are pressing a button

三世轮回 提交于 2021-01-29 08:59:07

问题


I have got a function. Below is a prototype

void onNewButtonPress(int64_t nanoseconds_timestamp, int32_t user_id);

A bit of destription. This function will be called each time a user with a user_id is pressing the button. Where nanoseconds_timestamp parameter is the time in nanoseconds since the epoch

This function will need to get the rate of user button presses, basically how many times per second a user pressed a button.

How can I calculate the rate for each user, store it and update it periodically? Is it possible to do it using just above function or I will have to create another function which will be called periodically and will calculate the rates.

How do I deal with users which started pressing button close to the end of the period. Do I need to average it?

I will be very interested to hear your opinions based on your experience.


回答1:


Something like this

Have a global/member variable that stores the users timestamps

std::map<int32_t, int64_t> lastClick;

Then calculate the difference and invert it to get the rate:

   void onNewButtonPress(int64_t nanoseconds_timestamp, int32_t user_id) {
      if (auto last = lastClick[user_id]) {
         auto rate = 1000000000 / (nanoseconds_timestamp - last);
         // Use the rate for something
         lastClick[user_id] = nanoseconds_timestamp;
      }
   }


来源:https://stackoverflow.com/questions/62836214/function-to-calculate-how-often-users-are-pressing-a-button

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!