DEV Community

Omais Ali
Omais Ali

Posted on

Measuring how long your MQL5 OnTick really takes

When an Expert Advisor feels slow on a VPS, people often guess at the cause. A better approach is to measure it. MQL5 gives you GetMicrosecondCount, which is enough to profile OnTick without any external tools.

The basic pattern

ulong g_total_us = 0;
ulong g_max_us   = 0;
long  g_calls    = 0;

void OnTick()
  {
   ulong start = GetMicrosecondCount();

   RunStrategy();   // your existing logic

   ulong took = GetMicrosecondCount() - start;
   g_total_us += took;
   g_calls++;
   if(took > g_max_us)
      g_max_us = took;
  }

void OnDeinit(const int reason)
  {
   if(g_calls > 0)
      PrintFormat("OnTick calls=%I64d avg=%.1f us max=%I64u us",
                  g_calls, (double)g_total_us / g_calls, g_max_us);
  }
Enter fullscreen mode Exit fullscreen mode

The average tells you the normal cost. The maximum tells you about the spikes, and the spikes are usually what hurts.

Time the pieces, not just the whole

Once you know OnTick is slow, wrap the suspects separately: indicator buffer copies, history selection, file writes and order sending. A common finding is that HistorySelect over the full account history on every tick costs far more than the strategy logic itself. Restrict the range, or cache results and refresh only on a new bar.

Log slow ticks as they happen

if(took > 50000)   // 50 ms
   PrintFormat("Slow tick: %I64u us at %s", took, TimeToString(TimeCurrent(), TIME_SECONDS));
Enter fullscreen mode Exit fullscreen mode

Keep the threshold high enough that the journal does not fill up, because printing is itself slow.

A few things to remember

  1. Measure on the same VPS the EA runs on. A desktop machine can be several times faster.
  2. Remove or reduce the profiling once you have your answer, or guard it behind an input flag.
  3. The Strategy Tester runs your code differently from live, so confirm timings on a demo chart too.

Knowing the real numbers turns a vague complaint about lag into a specific fix.

Top comments (0)