1
0

timeslicer.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include "precomp.h"
  2. #include "timeslicer.h"
  3. #define TIMER_SLICE 0x7816
  4. TimeSlicer::TimeSlicer(int percent_cpu_usage/* =50 */, int slice_duration/* =-1 */) {
  5. max_cpu_usage = MIN((float)percent_cpu_usage, 99.0f) / 100.0f;
  6. duration = slice_duration;
  7. started = 0;
  8. slicecount = 0;
  9. firstslicetime = -1;
  10. }
  11. TimeSlicer::~TimeSlicer() {
  12. }
  13. void TimeSlicer::startSlicer() {
  14. if (started) return;
  15. started = 1;
  16. timerclient_setTimer(TIMER_SLICE, duration);
  17. onSlicerStart();
  18. timerclient_timerCallback(TIMER_SLICE);
  19. }
  20. void TimeSlicer::stopSlicer() {
  21. if (!started) return;
  22. started = 0;
  23. timerclient_killTimer(TIMER_SLICE);
  24. onSlicerStop();
  25. firstslicetime = -1;
  26. }
  27. void TimeSlicer::onSlicerStop() {
  28. }
  29. void TimeSlicer::onSlicerStart() {
  30. }
  31. int TimeSlicer::isSlicerStarted() {
  32. return started;
  33. }
  34. void TimeSlicer::timerclient_timerCallback(int id) {
  35. if (id == TIMER_SLICE) {
  36. DWORD now = Std::getTickCount();
  37. runSlice(now, now + (int)((float)duration * max_cpu_usage));
  38. } else
  39. TimerClient::timerclient_timerCallback(id);
  40. }
  41. void TimeSlicer::runSlice(DWORD start, DWORD stopwhen) {
  42. DWORD now = Std::getTickCount();
  43. slicecount = 0;
  44. onBeginSliceBatch();
  45. if (slicecount == 0 && firstslicetime != -1) stopwhen = now + firstslicetime;
  46. while (Std::getTickCount() < stopwhen) {
  47. onSlice();
  48. slicecount++;
  49. if (!started) break; // got aborted
  50. }
  51. onEndSliceBatch();
  52. }