让CPU使用率为正弦曲线

来源:互联网 发布:c语言定义数组最大长度 编辑:程序博客网 时间:2024/05/16 05:17
  1. //伪代码
  2. int main()
  3. {
  4. int start_time, current_time;
  5. while(1)
  6. {
  7. start_time = GetCurrentTime();
  8. current_time = start_time;
  9. while(current_time - start_time < 60)
  10. current_time = GetCurrentTime();
  11. sleep(60);
  12. }
  13. }
关键是如何获取当前时间。Windows下可以使用GetTickCount(),Linux下可以使用gettimeofday()。
 
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. int main()
  4. {
  5. struct timeval tv;
  6. longlong start_time,end_time;
  7. while(1)
  8. {
  9. gettimeofday(&tv,NULL);
  10. start_time = tv.tv_sec*1000000 + tv.tv_usec;
  11. end_time = start_time;
  12. while((end_time - start_time) < 60000)
  13. {
  14. gettimeofday(&tv,NULL);
  15. end_time = tv.tv_sec*1000000 + tv.tv_usec;
  16. }
  17. usleep(60000);
  18. }
  19. return 0;
  20. }
  21. 现在我们用这种方法实现CPU使用率的正弦曲线。


    首先要确定这个曲线的函数。这个函数的最大值是1,最小值是0,因此肯定是0.5(sin(tx) + 1)。

    怎么确定t呢?

    我们可以认为,曲线的更新周期应该大于100ms,我们以100ms为单位,把100ms的平均使用率作为这100ms末的使用率。


    假如我们希望10s能出一个完整的波形,100ms计算一次,那就需要计算100次。这样我们要准备两个大小为100的数组,分别保存循环时间和睡眠时间。

    而且满足,第一个数组循环时间为0,睡眠时间为100,第50个数组循环时间为100,睡眠时间为0,第100个数组循环时间为0,睡眠时间为100.

    这样我们就确定了t了。100个数组下标为横坐标,那么周期是100,t=2x3.14/100 = 0.0628.

    代码如下:

    1. #include <stdio.h>
    2. #include <stdlib.h>
    3. #include <math.h>
    4. int main()
    5. {
    6. struct timeval tv;
    7. longlong start_time,end_time;
    8. longlong busy_time[100];
    9. longlong idle_time[100];
    10. int i;
    11. for(i = 0; i < 100; i++)
    12. {
    13. busy_time[i] = 100000 * 0.5 * (sin(i*0.0628) + 1);
    14. idle_time[i] = 100000 - busy_time[i];
    15. }
    16. i = 0;
    17. while(1)
    18. {
    19. gettimeofday(&tv,NULL);
    20. start_time = tv.tv_sec*1000000 + tv.tv_usec;
    21. end_time = start_time;
    22. while((end_time - start_time) < busy_time[i])
    23. {
    24. gettimeofday(&tv,NULL);
    25. end_time = tv.tv_sec*1000000 + tv.tv_usec;
    26. }
    27. usleep(idle_time[i]);
    28. i = (i+1)%100;
    29. }
    30. return 0;
    31. }

    效果还不错:


    上面的程序都是在单CPU下完成的。如果在多CPU下,可以指定此进程只运行在某个CPU上,不再赘述了。


0 0
原创粉丝点击