随分前だったので覚えていないのですが、おそらく比較コードのミスです。あらかじめ1万行いれておいたのは「更新系」をチェックする必要があったので、このままだと list のほうが有利に働きますよね。
気になったので Go4 と Go5 だけ抜き出して書き直しました。
実験コード
[code lang=”csharp”]
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
DataTable MakeDataTable()
{
var dt = new DataTable();
for (int i = 0; i < 100; i++)
{
dt.Columns.Add(new DataColumn("x" + i.ToString(), typeof(string)));
}
return dt;
}
double Go4()
{
var dt = MakeDataTable();// new DataTable();
// データ更新チェックのため、あらかじめ1万行を作る
for (int i = 0; i < 10000; i++)
{
var row = dt.NewRow();
dt.Rows.Add(row);
}
// 計測開始
var start = DateTime.Now;
var tm = DateTime.Now;
for (int i = 0; i < dt.Rows.Count; i++)
{
var row = dt.Rows[i];
for (int j = 0; j < 100; j++)
{
row[j] = tm.ToShortDateString(); tm.AddSeconds(1);
}
}
var tend = DateTime.Now;
var span = (tend – start).TotalSeconds;
return span;
}
double Go5()
{
var dt = new List<object>();
// データ更新チェックのため、あらかじめ1万行を作る
for (int i = 0; i < 10000; i++)
{
var row = new object[100];
dt.Add(row);
}
// 計測開始
var start = DateTime.Now;
var tm = DateTime.Now;
for (int i = 0; i < dt.Count; i++)
{
var row = dt[i] as object[];
for (int j = 0; j < 100; j++)
{
row[j] = tm.ToShortDateString(); tm.AddSeconds(1);
}
}
var tend = DateTime.Now;
var span = (tend – start).TotalSeconds;
return span;
}
/// <summary>
/// list を利用
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
var t = this.Go5();
label1.Text = t.ToString();
}
}
[/code]
どちらも、1万行いれておいて、その行に対して逐一データを修正するというスタイルになっています。
コードは Visual Studio 2013 を使っています。
実験結果
DataTable 8.32, 8.12, 8.12 sec
list 0.88, 0.83, 0.83 sec
とう具合に、DataTable よりも list のほうが 10 倍早くなっています。
すべてオンメモリで動くために、後は CPU 速度の違いになるとは思うのですが、PC が異なるし(こっちの PC のほうが断然早いので)相対的な結果になります。以前の 4,5倍よりも開きが大きくなっています。絶対値の違いは、VB が C# よりも遅いのではなくて、計測する CPU の差です。
カテゴリー:開発|DataTable よりも List を使うと 10 倍早くなる(続編) はコメントを受け付けていません
思い付きでやったので、準備不足…な感は否めませんが、ひとまずハンズオンっぽいものをやりました。.NETラボ勉強会の面子にビデオを撮ってもらったので、後で編集して Youtube 等に上げたいと思います。初動が悪かったので、Raspberry Pi の初心者ばかりが集まる=手ぶらでやってくる方がほとんどと思ったのですが、予想に反して Raspberry Pi 2 を持って来て下さった方が8名余りもいらっしゃいました。ありがとうございます。ちょっと、そっちのほうは予想しなかったので、ほぼ放置状態になってしまったのが申し訳ない/残念なのですが、ひとまず、Raspberry Pi 2 に Windows IoT Core を入れるのは結構大変である、ってのは実感して頂けたと思います。いやいや、あれだけ色々な人がやって、結構躓くのだから、家でひとりでやると2時間ぐらいうんうん唸ってしてまっても仕方がないのですよ。情報的には、英語のサイト Windows IoT – Get Started から辿れるところにありますが、各自の環境(Mac, Windows, 仮想環境, micro SD カードの状況などなど)が異なっていて、一筋縄にはいきません。挙句、終わりの5時頃にできたのは、LED をチカチカさせるところまでです。
ただし、その前に「どこで躓くのか?」を話したのと、後ろのほうで「何ができるのか?」を話したので、Hello world 的に Lチカを済ませた後に「どこに進めばよいのか」は何となく掴めたのではないか、とは思っています。Raspberry Pi 2 自体は 5,000円程度はするし、時間とお金を掛けるのであれば、それなりに「何か」を掴み取りたいものです。
土曜日には、あえて言いませんでしたが、Windows IoT Core on RPi で四苦八苦するよりは、Raspberry Pi にすんなり Rasbian を乗せて制御したほうが断然いいです。また、Linux に四苦八苦するよりは、Arduino を使ってさっくりとセンサー制御を学んだほうがいいです。そのあたりは、適材適所なところと、「将来的に何をするのか?」の目標を踏み間違えないようにすれば、無駄な学習をせずにすみます(勿論、あえて「無駄な学習」をして異なる知見を得る方法もあります。私もよくやりますが)。
開発環境が Windows 10 IP + Visual Studio 2015 RC となっていますが、現在の Windows 10 IP の build が非常に不安定なので、Windows 8.1 + VS2015RC の組み合わせも検討してみてください。.NET ラボのハンズオンでは半分ぐらいが Mac に Windows 10 IP を入れていましたが、最新のとそうでないものとが混在すると結構ややこしいです。
古い Windows 10 IP だと micro SD カードに書き込む dism のコマンドが異なっています。矛盾していますが、Windows 10 IP は新しいバージョンを使って micro SD カードに焼きこみます。ある意味、micro SD カードへの焼きこみだけ Windows 10 IP で行って、開発環境は Windows 8.1 + VS2015RC という組み合わせが安定します。ちなみに、Visual Studio 2013 と 2015RC は混在できています(これは安定しています)。
Windows 10 IP + Visual Studio 2015RC の組み合わせの場合、VS2015RC を立ち上げるときには「開発者モード」にする必要があります。そうしないと、Windows IoT の XAML デザイナが動きません(Windows 8.1 の場合は、もともと動かないので、気にする必要はありません)。デザイナを有効にするためには、「設定」→「Update & security」→「for Developers」を開いて設定します。ちょっと前の Windows 10 IP では、このページが落ちてしまうので Windows 10 を入れた直後に VS2015RC を入れて起動するとXAMLデザイナが動かないときの対処方法 | Moonmile Solutions Blog を参考にして、グループポリシーを設定してください。
少しぐらいは資料を用意すればよかったのと、事前に作っておいた(実は、超音波センサーのプログラムは前日…というか当日の夜に作ってあった)プログラムは、配布すればよかったですね。なんとなく、Raspberry Pi を各自動かしてみてから、の頭があったので配布し忘れていたのですが。
組み込みに関しては、全くやったことはないけど興味がある方から、自前で液晶ディスプレイを持参できる方までさまざまです。特に Windows IoT on RPi の場合には、もともと Raspberry Pi を使っている方は、それなりに機材が揃っている(自前のハット/拡張ボードとか)のでそれを使いたいものです。ちなみ、Raspberry Pi の既存のハットなのですが、Windows IoT のピン番号が異なっていたり融通が効かなかったりするので、ほとんど使えないと思います。I2C オンリーならば大丈夫かも、ってことで I2C ボードだけは検証します。残念ながら手元の Sparkfun のモータードライバは使えませんでした。
以前、Kickstarter で出ていた meArm も持ってきました。これはサーボモーターが4つ付いて 3,500円ぐらいです。英国産です。Raspberry Pi 用に Sparkfan で I2C ボードも買ってあるので、いずれ Windows IoT で動かしてみましょう。一年前に meArmPi の動作メモ | Moonmile Solutions Blog あたりで、Raspbian + mono + F# で動かしたことがあります。
半田付けの電子工作の例として、RealSense コンテストのとき作った妖怪ウォッチ LED も持って行きました。これは抵抗付きなので、そのまま Raspberry Pi のピンから給電しても大丈夫です。
私の場合、Internet of Things というよりも、動かせるモノからスタートしているので他とはちょっと毛色が違うのですが、具体的に「何かが動く」とか「何を操作できる」という入り口がいいかなと思っています。手元の Raspberry Pi 5 台は小学校でのワークショップ用に買ってはみたのですが、Windows IoT だとディスプレイがないとちょっと辛い感じ(Raspbian だとなおさら)なので、この辺りは考え直そうかなと思案中ですね。
次は何をするか?
Windows IoT Core で Lチカをやったり、モーターを制御できた後は何をするのか?が問題ですよね。ホビー的にマルチコプターに進むのもいいのですが、ワタクシ的には地べたを這いずり回るほうが「安全」なので、キャタピラと車輪とアームのほうに進みます。位置情報なんかは「確率ロボテック」を読むとよいでしょう。ルンバの位置情報はこれを使っているハズです。あと、カメラとアーム制御なんかは、ROS に対応させるのも良いかなと。
という訳で、.NET ラボ勉強会スタッフの皆様と、会場を提供してくださった Microsoft さんに感謝です。
参考資料
いくつか Windows IoT Core on Raspberry Pi で参考になりそうな書籍を上げておきます。
open System
open Android.App
open Android.Content
open Android.Runtime
open Android.Views
open Android.Widget
open Android.OS
open Android.Bluetooth
open System.Linq
open Java.Util
module ARDUINO =
let INPUT = 0
let OUTPUT = 1
let LOW = 0
let HIGH = 1
type Arduino() as this =
let INPUT = 0
let OUTPUT = 1
let LOW = 0
let HIGH = 1
let DIGITAL_MESSAGE = 0x90uy // send data for a digital port
let ANALOG_MESSAGE = 0xE0uy // send data for an analog pin (or PWM)
let REPORT_ANALOG = 0xC0uy // enable analog input by pin #
let REPORT_DIGITAL = 0xD0uy // enable digital input by port
let SET_PIN_MODE = 0xF4uy // set a pin to INPUT/OUTPUT/PWM/etc
let REPORT_VERSION = 0xF9uy // report firmware version
let SYSTEM_RESET = 0xFFuy // reset from MIDI
let START_SYSEX = 0xF0uy // start a MIDI SysEx message
let END_SYSEX = 0xF7uy // end a MIDI SysEx message
let mutable _socket:BluetoothSocket = null
let mutable autoStart = false
let mutable delay = 0
let mutable digitalOutputData = Array.zeroCreate(16)
let mutable digitalInputData = Array.zeroCreate(16)
let mutable analogInputData = Array.zeroCreate(16)
do
if autoStart = true then
delay <- 0
this.Connect()
this.Open()
/// Connect Bluetooth on Arduino.
member this.Connect() =
let adapter = BluetoothAdapter.DefaultAdapter
if adapter = null then
raise (Exception("No Bluetooth adapter found."))
if adapter.IsEnabled = false then
raise (Exception("Bluetooth adapter is not enabled."))
let device = adapter.BondedDevices.FirstOrDefault( fun x -> x.Name = "HC-06" )
if device = null then
raise (Exception("Named device not found."))
_socket <- device.CreateRfcommSocketToServiceRecord(UUID.FromString("00001101-0000-1000-8000-00805f9b34fb"))
_socket.Connect()
member this.Open() =
// let mutable command = Array.create<byte>(2)
for i=0 to 5 do
let command = [|
REPORT_ANALOG ||| byte(i)
1uy
|]
_socket.OutputStream.Write( command, 0, command.Length )
for i=0 to 1 do
let command = [|
REPORT_DIGITAL ||| byte(i)
1uy
|]
_socket.OutputStream.Write( command, 0, command.Length )
member this.Close() =
_socket.Close()
_socket <- null
member this.digitalRead(pin:int):int =
(digitalInputData.[pin >>> 3] >>> (pin &&& 0x07)) &&& 0x01
member this.analogRead(pin:int):int =
analogInputData.[pin]
member this.pinMode(pin,mode) =
let message = [|
SET_PIN_MODE
byte(pin)
byte(mode)
|]
_socket.OutputStream.Write( message, 0, message.Length )
member this.digitalWrite(pin,value) =
let portNumber = (pin >>> 3) &&& 0xFF
digitalOutputData.[portNumber] <-
if value = 0 then
digitalOutputData.[portNumber] &&& ~~~(1 <<< (pin &&& 0x07))
else
digitalOutputData.[portNumber] ||| (1 <<< (pin &&& 0x07))
let message = [|
DIGITAL_MESSAGE ||| byte(portNumber)
byte(digitalOutputData.[portNumber] &&& 0x7F)
byte(digitalOutputData.[portNumber] >>> 7)
|]
_socket.OutputStream.Write(message, 0, message.Length);
[code lang=”vb”]
type MainActivity () =
inherit Activity ()
let mutable buttonConnect:Button = null
let mutable buttonOpen:Button = null
let mutable buttonLedOn:Button = null
let mutable buttonLedOff:Button = null
let mutable arduino:Arduino = new Arduino()
override this.OnCreate (bundle) =
base.OnCreate (bundle)
// Set our view from the "main" layout resource
this.SetContentView (Resource_Layout.Main)
// Get our button from the layout resource, and attach an event to it
buttonConnect <- this.FindViewById<Button>(Resource_Id.buttonConnect)
buttonOpen <- this.FindViewById<Button>(Resource_Id.buttonOpen)
buttonLedOn <- this.FindViewById<Button>(Resource_Id.buttonLEDon)
buttonLedOff <- this.FindViewById<Button>(Resource_Id.buttonLEDoff)
buttonConnect.Click.Add( fun args ->
arduino.Connect();
buttonConnect.Text <- "connected.";
)
buttonOpen.Click.Add( fun args ->
arduino.Open();
buttonConnect.Text <- "Firmata opend.";
arduino.pinMode(5, ARDUINO.OUTPUT );
arduino.digitalWrite(5, ARDUINO.LOW);
)
buttonLedOn.Click.Add( fun e -> this.OnClickLedOn(buttonLedOn,e) )
buttonLedOff.Click.Add( fun e -> this.OnClickLedOff(buttonLedOff,e) )
member this.OnClickLedOn(sender,e) =
arduino.digitalWrite(5, ARDUINO.HIGH)
member this.OnClickLedOff(sender,e) =
arduino.digitalWrite(5, ARDUINO.LOW)
[/code]
ざっくりと移植したのが以下です。Android の Bluetooth を使うために、BluetoothAdapter.DefaultAdapter を利用しています。
[code lang=”csharp”]
class Arduino
{
public static int INPUT = 0;
public static int OUTPUT = 1;
public static int LOW = 0;
public static int HIGH = 1;
private const int MAX_DATA_BYTES = 32;
private const int DIGITAL_MESSAGE = 0x90; // send data for a digital port
private const int ANALOG_MESSAGE = 0xE0; // send data for an analog pin (or PWM)
private const int REPORT_ANALOG = 0xC0; // enable analog input by pin #
private const int REPORT_DIGITAL = 0xD0; // enable digital input by port
private const int SET_PIN_MODE = 0xF4; // set a pin to INPUT/OUTPUT/PWM/etc
private const int REPORT_VERSION = 0xF9; // report firmware version
private const int SYSTEM_RESET = 0xFF; // reset from MIDI
private const int START_SYSEX = 0xF0; // start a MIDI SysEx message
private const int END_SYSEX = 0xF7; // end a MIDI SysEx message
// private SerialPort _serialPort;
private int delay;
private int waitForData = 0;
private int executeMultiByteCommand = 0;
private int multiByteChannel = 0;
private int[] storedInputData = new int[MAX_DATA_BYTES];
private bool parsingSysex;
private int sysexBytesRead;
/// String specifying the name of the serial port. eg COM4
/// The baud rate of the communication. Default 115200
/// Determines whether the serial port should be opened automatically.
/// use the Open() method to open the connection manually.
/// Time delay that may be required to allow some arduino models
/// to reboot after opening a serial connection. The delay will only activate
/// when autoStart is true.
public Arduino(string serialPortName, Int32 baudRate, bool autoStart, int delay)
{
/*
_serialPort = new SerialPort(serialPortName, baudRate);
_serialPort.DataBits = 8;
_serialPort.Parity = Parity.None;
_serialPort.StopBits = StopBits.One;
*/
if (autoStart)
{
this.delay = delay;
this.Connect();
this.Open();
}
}
///
/// Creates an instance of the Arduino object, based on a user-specified serial port.
/// Assumes default values for baud rate (115200) and reboot delay (8 seconds)
/// and automatically opens the specified serial connection.
///
/// String specifying the name of the serial port. eg COM4
public Arduino(string serialPortName) : this(serialPortName, 115200, true, 8000) { }
///
/// Creates an instance of the Arduino object, based on user-specified serial port and baud rate.
/// Assumes default value for reboot delay (8 seconds).
/// and automatically opens the specified serial connection.
///
/// String specifying the name of the serial port. eg COM4
/// Baud rate.
public Arduino(string serialPortName, Int32 baudRate) : this(serialPortName, baudRate, true, 8000) { }
///
/// Creates an instance of the Arduino object using default arguments.
/// Assumes the arduino is connected as the HIGHEST serial port on the machine,
/// default baud rate (115200), and a reboot delay (8 seconds).
/// and automatically opens the specified serial connection.
///
public void Connect()
{
BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;
if (adapter == null)
{
throw new Exception(“No Bluetooth adapter found.”);
}
if (!adapter.IsEnabled)
{
throw new Exception(“Bluetooth adapter is not enabled.”);
}
BluetoothDevice device = (from bd in adapter.BondedDevices
where bd.Name == “HC-06”
select bd).FirstOrDefault();
if (device == null)
{
throw new Exception(“Named device not found.”);
}
_socket = device.CreateRfcommSocketToServiceRecord(UUID.FromString(“00001101-0000-1000-8000-00805f9b34fb”));
_socket.Connect();
return;
}
///
/// Opens the serial port connection, should it be required. By default the port is
/// opened when the object is first created.
///
public void Open()
{
// _serialPort.Open();
// Thread.Sleep(delay);
byte[] command = new byte[2];
for (int i = 0; i < 6; i++)
{
command[0] = (byte)(REPORT_ANALOG | i);
command[1] = (byte)1;
// _serialPort.Write(command, 0, 2);
_socket.OutputStream.Write(command, 0, command.Length);
}
for (int i = 0; i < 2; i++)
{
command[0] = (byte)(REPORT_DIGITAL | i);
command[1] = (byte)1;
// _serialPort.Write(command, 0, 2);
_socket.OutputStream.Write(command, 0, command.Length);
}
command = null;
/*
if (readThread == null)
{
readThread = new Thread(processInput);
readThread.Start();
}
*/
}
///
/// Closes the serial port.
///
/// Lists all available serial ports on current system.
///
/// An array of strings containing all available serial ports.
public static string[] list()
{
// return SerialPort.GetPortNames();
return new string[] { “HC-06” };
}
///
/// Returns the last known state of the digital pin.
///
/// The arduino digital input pin.
/// Arduino.HIGH or Arduino.LOW
public int digitalRead(int pin)
{
return (digitalInputData[pin >> 3] >> (pin & 0x07)) & 0x01;
}
///
/// Returns the last known state of the analog pin.
///
/// The arduino analog input pin.
/// A value representing the analog value between 0 (0V) and 1023 (5V).
public int analogRead(int pin)
{
return analogInputData[pin];
}
///
/// Sets the mode of the specified pin (INPUT or OUTPUT).
///
/// The arduino pin.
/// Mode Arduino.INPUT or Arduino.OUTPUT.
public void pinMode(int pin, int mode)
{
byte[] message = new byte[3];
message[0] = (byte)(SET_PIN_MODE);
message[1] = (byte)(pin);
message[2] = (byte)(mode);
// _serialPort.Write(message, 0, 3);
_socket.OutputStream.Write(message, 0, message.Length);
message = null;
}
///
/// Write to a digital pin that has been toggled to output mode with pinMode() method.
///
/// The digital pin to write to.
/// Value either Arduino.LOW or Arduino.HIGH.
public void digitalWrite(int pin, int value)
{
int portNumber = (pin >> 3) & 0x0F;
byte[] message = new byte[3];
const int pinLedRed = 13;
const int pinLedYellow = 12;
const int pinLedBlue = 11;
const int pinMotorAPower = 10;
const int pinMotorAOut1 = 9;
const int pinMotorAOut2 = 8;
const int pinMotorBPower = 5;
const int pinMotorBOut1 = 6;
const int pinMotorBOut2 = 7;
void OnLedPressed(object sender, PointerRoutedEventArgs e)
{
if (sender == ledRed) arduino.digitalWrite(pinLedRed, PinState.HIGH);
if (sender == ledYellow) arduino.digitalWrite(pinLedYellow, PinState.HIGH);
if (sender == ledBlue) arduino.digitalWrite(pinLedBlue, PinState.HIGH);
}
void OnLedReleased(object sender, PointerRoutedEventArgs e)
{
if (sender == ledRed) arduino.digitalWrite(pinLedRed, PinState.LOW);
if (sender == ledYellow) arduino.digitalWrite(pinLedYellow, PinState.LOW);
if (sender == ledBlue) arduino.digitalWrite(pinLedBlue, PinState.LOW);
}
void OnTankPressed(object sender, PointerRoutedEventArgs e)
{
if (sender == tankForward) { MotorLeftForward(); MotorRightForward(); };
if (sender == tankBack) { MotorLeftBack(); MotorRightBack(); };
if (sender == tankLeft) { MotorLeftBack(); MotorRightForward(); };
if (sender == tankRight) { MotorLeftForward(); MotorRightBack(); };
この時、Arduino 側に差し込む Bluetooth のシリアル通信速度を設定し直します。デフォルトでは、57600 のように高速になっているので、HC-05 の初期値の 9600 に設定し直します。このあたりは、手持ちの Bluetooth モジュールに合わせます(私の AT コマンドが面倒で、そのまま 9600 で使っています)
Firmata.begin(9600);
Windows Remote Arduino のライブラリをダウンロードする
Windows IoT – SetupPCWRA の Option 1: Install the NuGet package を使えば、一発で Nuget で取れるようなことが書いてありますが…まだ、NuGet 上にはありません(Windows 8.1からも見つからない)。仕方がないので github からダウンロードしてビルドをします。
[code lang=”csharp”]
public MainPage()
{
this.InitializeComponent();
// bluetooth = new BluetoothSerial("RNBT-E072");
bluetooth = new BluetoothSerial("HC-06");
arduino = new RemoteDevice(bluetooth);
bluetooth.ConnectionEstablished += OnConnectionEstablished;
//these parameters don’t matter for bluetooth
bluetooth.begin(9600, SerialConfig.SERIAL_8N1);
}
[/code]
ここでも、シリアル通信の速度「9600」と、Bluetooth モジュールの名前「HC-05」のように設定し直しておきます。あとは、x86 あたりでビルドをすれば ok です。x64 でビルドをすると XAML デザイナが動かないので、ひとまず x86 で動作確認するとよいでしょう。Any CPU で動かないのは C++/CX を使っているためです。
[code lang=”csharp”]
private void OnConnectionEstablished()
{
//enable the buttons on the UI thread!
var action = Dispatcher.RunAsync( Windows.UI.Core.CoreDispatcherPriority.Normal, new Windows.UI.Core.DispatchedHandler( () => {
OnButton.IsEnabled = true;
OffButton.IsEnabled = true;
}));
}
private void OnButton_Click( object sender, RoutedEventArgs e )
{
//turn the LED connected to pin 5 ON
arduino.digitalWrite( 5, PinState.HIGH );
}
private void OffButton_Click( object sender, RoutedEventArgs e )
{
//turn the LED connected to pin 5 OFF
arduino.digitalWrite( 5, PinState.LOW );
}
[/code]
Bluetooth とペアリングする
Windows 8.1 のとき、BT2.0を接続する場合はペアリングが必要です。Windows 10 で BLE 接続する場合はペアリングなしでいけるらしいのですが、そこはまだ確認してません。
HC-05 のピンコードは「1234」です。
Arduino Uno で動かす
Bluetooth モジュールへの配線は MS のサイト で確認してもらうとして(RX/TXを接続するだけの簡単なものです)Uno 互換機で動かした結果がこんな感じです。