Infinite looping consumes 100% CPU

给你一囗甜甜゛ 提交于 2020-01-03 21:14:32

问题


I am stuck in a situation where I need to generate a defined frequency of some Hz. I have tried multimedia timers and all other stuff available on the internet but so far an infinite loop with some if-else conditions gave me the best results. But the problem in this approach is that it consumes almost all of the cpu leaving no space for other applications to work properly.

I need an algorithm with either generates frequency of some Hz to KHz.

I am using windows plateform with C#.


回答1:


You can't accurately generate a signal of a fixed frequency on a non-realtime platform. At any moment, a high priority thread from same or other process could block the execution of your thread. E.g. when GC thread kicks in, worker threads will be suspended.

That being said, what is the jitter you are allowed to have and what is the highest frequency you need to support?




回答2:


The way I would approach the problem would be to generate a "sound wave" and output in on the sound card. There are ways to access your sound card from C#, e.g. using XNA. As others have pointed out, using the CPU for that isn't a good approach.




回答3:


Use Thread.Sleep(delay); in your loop

it's reduce processor usage




回答4:


As you are generating a timer, You would want to Sleep based on the period of your frequency.

You will have to run your frequency generator in its own thread and call

Thread.Sleep(yourFrequencyPeriodMs);

in each iteration of period.



来源:https://stackoverflow.com/questions/12729075/infinite-looping-consumes-100-cpu

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