【问题标题】:Raspberry Pi, Mono, and Trig FunctionsRaspberry Pi、Mono 和 Trig 函数
【发布时间】:2013-11-29 01:11:26
【问题描述】:

我正在尝试使用 raspberry pi 作为合成器,但遇到了一些非常奇怪的行为。我制作了一个非常简单的正弦波振荡器进行测试,并注意到该振荡器正在最大限度地消耗 CPU。

我的代码:

using System;
using System.Threading;
namespace OSCTest
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            System.Threading.Timer timer = new Timer(process, null, 1000, 1000);
            Console.WriteLine ("Running.");
            Console.ReadLine ();
            timer.Dispose();
        }
        public static void process(object state)
        {
            for (int i = 0; i < 44100; i++)
            {
                float j;
                j = (float)Math.Sin(2f * Math.PI * i * 1000f);
            }
        }
    }
}

这个简单的程序完全最大化了 RPi 的 cpu 并重复创建线程来处理传入的计时器滴答事件。

我知道与简单的数学函数相比,三角函数被认为是相当昂贵的,所以我取出了 sin 计算并再次运行了程序。

using System;
using System.Threading;
namespace OSCTest
{
    class MainClass
    {
        public static void Main (string[] args)
        {
            System.Threading.Timer timer = new Timer(process, null, 1000, 1000);
            Console.WriteLine ("Running.");
            Console.ReadLine ();
            timer.Dispose();
        }
        public static void process(object state)
        {
            for (int i = 0; i < 44100; i++)
            {
                float j;
                j = (float)(2f * Math.PI * i * 1000f);
            }
        }
    }
}

在运行上述示例时,Pi 甚至不会闪烁,从字面上看,top 报告可执行文件的 CPU 使用率为 0.0%。

所以我的问题是,是什么导致了极度放缓?是 RPi 无法很好地计算 sin 吗?它是特定于 pi 上的单声道运行时的东西吗?是不是更深层次的东西我不理解?

编辑:重新格式化的代码示例。

【问题讨论】:

  • 是的,我注意到代码格式已关闭,我刚刚进行了编辑。

标签: c# mono arm raspberry-pi trigonometry


【解决方案1】:

请考虑这样一个事实,即 Timer 每 1000 毫秒调用一次 process 函数,如果 process 函数太慢而无法在 1000 毫秒内完成,则调用可能会重叠。

这会使 CPU 因过多的线程而膨胀并使系统变得迟缓。

您可以对process 函数进行标志检查,以确保它在任何给定时间点由一个线程执行。

【讨论】:

    猜你喜欢
    • 2012-04-30
    • 2014-10-24
    • 2013-04-20
    • 1970-01-01
    • 2015-08-24
    • 2017-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多