并行交易软件
我的交易软件很慢,我想提升它。 有两个瓶颈。
第一个瓶颈:
当收到新的数据集(新报价,交易等)时,所有策略都需要尽快更新。 他们需要重新计算他们的状态/命令等。当准备好读取新的数据束时,调用AllTablesUpdated
方法。 此方法为每个特定策略调用AllTablesUpdated
方法。
public void AllTablesUpdated() { Console.WriteLine("Start updating all tables."); foreach (Strategy strategy in strategies) { strategy.AllTablesUpdated(); } Console.WriteLine("All tables updated in " + sw.ElapsedMilliseconds); }
结果推迟了。 有时需要0或1毫秒(非常好),有时需要8-20毫秒,但有时需要800毫秒
当前实现存在两个问题:
- 它使用一个线程,因此不使用多核处理器
- strategy.AllTablesUpdated()使用共享资源,可能会被阻止一段时间。 如果某个特定策略正在等待资源被释放,那么所有其他策略也在等待(相反,我们可以某种方式推迟阻止策略并开始处理其他策略吗?)
第二个瓶颈非常相似:
private OrdersOrchestrator() { // A simple blocking consumer with no cancellation. Task.Factory.StartNew(() => { while (!dataItems.IsCompleted) { OrdersExecutor ordersExecutor = null; // Blocks if number.Count == 0 // IOE means that Take() was called on a completed collection. // Some other thread can call CompleteAdding after we pass the // IsCompleted check but before we call Take. // In this example, we can simply catch the exception since the // loop will break on the next iteration. try { ordersExecutor = dataItems.Take(); } catch (InvalidOperationException) { } if (ordersExecutor != null) { ordersExecutor.IssueOrders(); } } }); }
ordersExecutor
可能会等到某些资源被释放。 如果是这样,所有其他ordersExecutors
都被阻止。
详细信息:每个strategy
包含一个ordersExecutor
,它们使用共享资源。 strategy.AllTablesUpdated()
可以等待它的ordersExecutor
释放资源,反之亦然。 如果出现这种情况,其他所有stretegies/ordersExecutors
也会被阻止。 有100多个策略。
如何修改代码来实现?:
- 如果一个
strategy
或ordersExecutor
被阻止,其他人不应被阻止? - 使用多核处理器和可能的多处理器平台的力量?
您的问题相当广泛,您基本上要问的是如何在您的应用程序中使用并行性? 您已经将代码分解为离散任务,因此使用并行应该不是一个大问题。 我建议阅读有关PLinq和TPL的内容,两者都提供易于使用的API,用于此类事情:
http://www.codeproject.com/KB/dotnet/parallelism-in-net-4-0.aspx