<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Selda Turgut on Medium]]></title>
        <description><![CDATA[Stories by Selda Turgut on Medium]]></description>
        <link>https://medium.com/@seldaturgut2020?source=rss-4bef563f249e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Vz3s8QTG6VFJLZ1TkZ138g@2x.jpeg</url>
            <title>Stories by Selda Turgut on Medium</title>
            <link>https://medium.com/@seldaturgut2020?source=rss-4bef563f249e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 08:50:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@seldaturgut2020/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Performance Trade-offs of Lock-Free Data Structures]]></title>
            <link>https://medium.com/@seldaturgut2020/the-performance-trade-offs-of-lock-free-data-structures-43104d77611c?source=rss-4bef563f249e------2</link>
            <guid isPermaLink="false">https://medium.com/p/43104d77611c</guid>
            <category><![CDATA[lock-free-programming]]></category>
            <category><![CDATA[lock-free]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[new-ac-system-wayland]]></category>
            <category><![CDATA[multithreading]]></category>
            <dc:creator><![CDATA[Selda Turgut]]></dc:creator>
            <pubDate>Sun, 04 Oct 2026 16:11:23 GMT</pubDate>
            <atom:updated>2026-10-04T16:11:23.372Z</atom:updated>
            <content:encoded><![CDATA[<h3>Abstract</h3><p>Lock-free data structures are frequently associated with high-performance concurrent programming because they avoid the explicit mutual exclusion imposed by conventional locking mechanisms. However, the absence of locks does not imply the absence of synchronization costs, nor does lock-freedom itself provide a guarantee of superior execution performance. Lock-free algorithms replace blocking synchronization with other forms of coordination, most notably atomic read-modify-write operations, retry-based execution, cache-coherence communication, memory-ordering constraints, and, for dynamically allocated structures, safe memory reclamation.</p><p>These costs arise at different layers of the system and are strongly interconnected. Contention can increase the frequency of failed atomic operations, while repeated modification of shared state can generate additional coherence traffic between processor cores. Memory-ordering requirements constrain how operations may be observed across threads, and safe reclamation introduces further synchronization and bookkeeping to ensure that removed objects are not reclaimed while still accessible by concurrent operations. As a result, evaluating lock-free data structures requires a distinction between their theoretical progress guarantees and their practical performance characteristics.</p><p>This article examines the principal sources of performance overhead in lock-free data structures and explains how synchronization costs shift rather than disappear when locks are removed. The discussion focuses on progress guarantees, atomic synchronization, contention, cache coherence, memory ordering, and safe memory reclamation, providing a systems-level perspective on the trade-offs inherent in lock-free design.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YJCTCaSxRAGnt_UPUNbe0w.png" /></figure><h3><strong>Introduction</strong></h3><p>The increasing prevalence of multicore processors has made concurrency a fundamental concern in modern software systems. Applications that once relied primarily on improvements in single-core execution speed increasingly obtain performance through parallel execution across multiple processing cores. This shift creates a fundamental engineering problem: when several threads operate concurrently, they often need to access and modify the same data structures. Maintaining the consistency of this shared state requires synchronization.</p><p>The conventional solution is mutual exclusion. A mutex protects a critical section by allowing only one thread to execute it at a time. This model provides a relatively straightforward way to reason about correctness: a thread acquires the lock, modifies the protected state, and releases the lock when the operation is complete. Other threads attempting to enter the same critical section must wait until ownership becomes available. For many applications, this approach remains both appropriate and efficient.</p><p>The difficulty appears when synchronization itself becomes a significant part of the system’s behavior. Under contention, threads may compete for the same lock, execution may become serialized, and progress of one thread may depend directly on another thread releasing a resource. These characteristics have motivated decades of research into <strong>non-blocking synchronization</strong>, including lock-free data structures that coordinate concurrent operations without relying on mutual exclusion as their primary synchronization mechanism.</p><p>Lock-free algorithms typically achieve this through atomic operations such as compare-and-exchange. Rather than preventing competing threads from accessing shared state, an operation may proceed optimistically: it observes the current state, computes a desired transition, and attempts to publish that transition atomically. If another thread has modified the state in the meantime, the atomic update fails and the operation may retry using the newly observed state.</p><p>At first glance, this model suggests an appealing intuition. If waiting for locks can be expensive, eliminating locks should make the implementation faster. Yet this reasoning conflates two different properties: <strong>progress and performance</strong>.</p><p>This distinction becomes particularly apparent when studying concurrent data structures beyond their abstract algorithms. In practical work with lock-free structures, I found that removing explicit locking did not remove synchronization from the system. Instead, it made other forms of synchronization considerably more visible. Atomic operations, retries, memory visibility, cache behavior, and the lifetime of dynamically allocated objects all became part of the performance problem. What initially appears to be a question about avoiding locks therefore develops into a broader question about how concurrent operations interact with both the language memory model and the underlying hardware.</p><p>This observation motivates the central argument of this article:</p><blockquote><strong><em>Lock-free synchronization does not eliminate the cost of coordination; it changes where and how that cost is paid.</em></strong></blockquote><p>This distinction is important because the term <em>lock-free</em> describes a formal progress property. It does not state how many processor cycles an operation requires, how frequently an atomic update must be retried, how much coherence traffic is generated between cores, or how expensive it is to determine when removed memory can safely be reclaimed. An implementation can satisfy the formal requirements of lock-freedom while still exhibiting substantial synchronization overhead.</p><p>Understanding these costs requires examining lock-free algorithms across several abstraction layers. At the algorithmic level, contention can cause optimistic operations to fail and retry. At the language level, atomic operations and memory-ordering rules determine which observations between threads are valid. At the hardware level, multiple cores modifying shared cache lines require cache-coherence mechanisms to coordinate ownership and visibility. In dynamically allocated structures, another problem emerges: removing an object from a data structure does not necessarily mean that no concurrent thread can still access it.</p><p>The performance characteristics of lock-free data structures therefore cannot be understood solely by observing that they contain no mutex. They emerge from the interaction between the algorithm, the memory model, and the processor architecture.</p><p>The following sections examine these interactions in detail, beginning with the theoretical meaning of lock-freedom itself. Establishing that definition is essential because it reveals the first and perhaps most important distinction in the subject: a guarantee that a concurrent system continues to make progress is fundamentally different from a guarantee that it does so efficiently.</p><h3>Lock-Freedom as a Progress Guarantee</h3><p>The term lock-free is often interpreted informally as meaning that an algorithm performs its operations without using mutexes. Although the absence of traditional locks is an important characteristic of many lock-free implementations, this description does not capture the formal meaning of lock-freedom. In concurrent algorithm theory, lock-freedom belongs to a broader class of progress guarantees that describe whether operations can continue to complete when multiple threads execute concurrently. These guarantees concern the ability of the system to make progress rather than the amount of time or computational work required to achieve that progress.</p><p>In a blocking algorithm, the progress of one thread may depend on the behavior of another. A thread attempting to enter a critical section protected by a mutex, for example, cannot continue until the thread currently holding the mutex releases it. If the lock holder is delayed by the operating-system scheduler, suspended for an extended period, or otherwise prevented from executing, other threads waiting for the same lock may also be delayed. This dependency is one of the principal characteristics that non-blocking algorithms attempt to avoid.</p><p>Lock-free algorithms provide a different form of progress. Rather than guaranteeing that every individual operation completes within a bounded number of steps, lock-freedom guarantees system-wide progress. When multiple threads repeatedly attempt operations, the system cannot remain indefinitely in a state in which every operation fails to complete. Informally, even if some threads repeatedly lose contention and retry their operations, at least one competing operation must continue to complete.</p><p>Consider two threads attempting to update the same shared state using compare-and-exchange. Both threads may initially observe the same value and independently calculate their next state. Only one of those state transitions can succeed if both depend on the original value. Once one thread successfully publishes its update, the compare-and-exchange operation performed by the other thread fails because its expected state is no longer current. The unsuccessful thread must then observe the updated state and retry its operation.</p><p>From the perspective of the unsuccessful thread, work has been performed without completing the intended operation. From the perspective of the lock-free progress guarantee, however, the system has successfully progressed because another thread completed its operation. This distinction is central to understanding why lock-freedom and performance should not be treated as equivalent concepts.</p><p>A stronger progress guarantee is provided by wait-free algorithms. Wait-freedom requires every operation to complete within a bounded number of its own execution steps, regardless of the behavior of other threads. A particular thread therefore cannot be forced to retry indefinitely because competing threads repeatedly succeed first. This is stronger than lock-freedom, where system-wide progress is guaranteed but starvation of an individual operation remains possible.</p><p>Another related property is obstruction-freedom. An obstruction-free operation is guaranteed to make progress when it eventually executes in isolation for sufficiently long. Unlike lock-freedom, it does not require system-wide progress while threads continue to interfere with one another. The distinction between these guarantees establishes a useful hierarchy: obstruction-freedom provides a weaker progress condition, lock-freedom guarantees global progress under contention, and wait-freedom additionally provides bounded progress for every individual operation.</p><p>These definitions reveal an important limitation of using the term lock-free as an indicator of performance. None of these progress guarantees specifies how expensive a successful operation is. They do not establish how many atomic instructions must be executed, how frequently an operation may need to retry, how much communication occurs between processor cores, or how much auxiliary work is required to manage memory safely. A lock-free operation may complete only after several failed attempts, while a lock-based operation under favorable conditions may acquire an uncontended mutex and complete immediately.</p><p>The distinction becomes even more significant under high contention. Suppose several threads repeatedly attempt to modify the same atomic state. Each successful update demonstrates that the lock-free progress condition is being satisfied. At the same time, that successful update may invalidate assumptions made by several competing threads, causing their atomic operations to fail and forcing them to retry. The system therefore continues to make formal progress while performing an increasing amount of work per completed operation.</p><p>This leads to a fundamental distinction between progress and efficiency. Progress guarantees answer questions about whether concurrent operations can become indefinitely dependent on one another. Performance analysis instead concerns quantities such as computational overhead, latency, throughput, memory traffic, and scalability. An algorithm can provide a stronger progress guarantee while requiring more work to perform a particular operation.</p><p>The absence of explicit locking should therefore not be interpreted as the absence of synchronization. Lock-free algorithms still require threads to establish agreement about modifications to shared state. Rather than expressing this coordination through ownership of a mutex, they commonly express it through atomic state transitions and carefully defined memory-ordering relationships. The synchronization mechanism changes, but the underlying requirement for coordination remains.</p><p>This observation provides the transition from the theoretical definition of lock-freedom to its practical costs. Once mutual exclusion is replaced by optimistic concurrent updates, atomic operations become one of the primary mechanisms through which threads coordinate. Understanding the performance characteristics of lock-free data structures consequently requires examining not only how these operations preserve correctness, but also what they require from the processor and memory system.</p><h3>The Cost of Atomic Synchronization</h3><p>Atomic operations form the foundation of many lock-free algorithms. They allow multiple threads to observe and modify shared state without exposing intermediate states that could violate the consistency of the data structure. Among these operations, compare-and-exchange is particularly important because it enables an algorithm to express a conditional state transition: modify a shared value only if it still contains the value that was previously observed.</p><p>This mechanism enables optimistic concurrency. Instead of acquiring exclusive ownership before beginning an operation, a thread can read the current state, compute the modification it intends to perform, and then attempt to commit that modification atomically. If the state has not changed in the meantime, the operation succeeds. If another thread has modified it, the atomic operation fails and the algorithm can reconsider its assumptions before attempting another update.</p><p>The advantage of this approach is that a thread does not necessarily need to wait for another thread to leave a critical section. Independent progress remains possible, and a delayed thread does not automatically prevent all other threads from completing their operations. However, replacing mutual exclusion with atomic state transitions does not make those transitions equivalent to ordinary memory accesses.</p><p>A conventional load or store primarily concerns the movement of data between a processor and its memory hierarchy. An atomic read-modify-write operation has stronger requirements. The processor must ensure that the read, modification, and write are observed as a single indivisible operation with respect to competing accesses governed by the memory model. When the relevant state is shared across processor cores, maintaining this property requires coordination with the cache-coherence mechanisms of the underlying architecture.</p><p>The performance cost of an atomic operation therefore cannot be understood solely in terms of the instruction itself. Its cost also depends on where the relevant cache line resides, whether another core currently holds it in a conflicting coherence state, how frequently ownership of that line changes, and how many processors are simultaneously attempting to modify the same state. An atomic operation on data accessed primarily by one core may behave very differently from the same operation performed on a heavily contended cache line.</p><p>Compare-and-exchange introduces another important characteristic: failure is part of the algorithm. A failed operation is not necessarily an exceptional condition. It can be the expected consequence of another thread successfully changing the shared state first. Correct lock-free algorithms are therefore frequently structured around retry loops in which a thread repeatedly observes state, derives a new state, and attempts to publish it.</p><p>This changes the interpretation of synchronization overhead. With a mutex, contention is often visible as waiting for ownership of the lock. In a lock-free algorithm, contention may instead appear as additional execution: repeated loads, failed atomic operations, recomputation, and further attempts to update shared state. The thread remains active, but active execution should not automatically be interpreted as productive execution.</p><p>Atomic synchronization consequently represents a trade-off rather than the simple removal of a cost. It can eliminate important disadvantages associated with blocking and can provide stronger system-wide progress properties, but it introduces synchronization costs whose magnitude depends strongly on contention and the memory hierarchy. To understand why these costs can increase as concurrency grows, the next step is to examine what happens when several threads repeatedly compete to modify the same shared state.</p><h3>Contention, Retry Loops, and Wasted Work</h3><p>Contention arises when multiple threads attempt to access or modify the same shared state within overlapping periods of execution. In lock-free algorithms, contention is particularly important because synchronization is often optimistic. A thread proceeds under the assumption that the state it has observed will remain valid long enough for its intended update to succeed. When another thread modifies that state first, the assumption becomes invalid and the operation must be reconsidered.</p><p>Compare-and-exchange makes this behavior explicit. A thread reads a shared value, computes a desired update, and attempts to replace the original value only if it has not changed. When several threads perform this sequence concurrently, they may all begin from the same observed state, but only one conflicting update can succeed. The remaining operations fail because their expected values no longer correspond to the current state.</p><p>A failed compare-and-exchange preserves correctness, but it is not free. Before discovering the conflict, a thread may already have loaded shared data, traversed part of a structure, calculated a new pointer or index, or performed other preparatory work. Depending on the algorithm, some or all of this work may have to be repeated after the failure. The operation therefore consumes processor resources without producing a completed modification to the abstract data structure.</p><p>This distinction suggests an important separation between executed work and useful work. A processor can remain continuously active while only a fraction of its instructions contribute directly to completed operations. Under low contention, the difference may be small because atomic updates frequently succeed on their first attempt. As contention increases, however, a greater proportion of execution may be devoted to failed attempts and subsequent retries.</p><p>The resulting behavior can be counterintuitive. Adding more threads increases the amount of available computational parallelism, but it can also increase the number of threads competing for the same synchronization point. Beyond a certain level of contention, additional concurrency may therefore produce additional interference rather than proportionally more useful work. The algorithm remains lock-free because successful operations continue to occur, yet the amount of computation required for each successful operation can increase.</p><p>Retry loops also create a feedback effect. A failed atomic update causes a thread to retry, and the retry itself introduces another competing access to the same shared state. When many threads behave this way simultaneously, the synchronization point may experience a continuous stream of atomic read-modify-write operations. The cost is therefore not limited to the original conflict. Repeated attempts can themselves contribute to further contention.</p><p>This behavior illustrates why lock-free progress guarantees must be interpreted carefully. Lock-freedom prevents the system from reaching a state in which all operations remain permanently blocked by one another, but it does not require every unit of computation to contribute efficiently to progress. A system may satisfy the lock-free property while repeatedly discarding speculative work because competing operations invalidate one another.</p><p>The structure of the data structure determines how severe this effect becomes. Algorithms that concentrate synchronization around a small number of shared variables can create natural contention points. A frequently modified head pointer, tail pointer, counter, or global state word may become a location through which many operations must pass. In contrast, designs that distribute modifications across independent memory locations can reduce direct interference between threads. The scalability of a lock-free structure therefore depends not only on whether it uses atomic operations, but also on how those operations are distributed throughout the algorithm.</p><p>Contention also interacts with the duration of an operation. The longer the interval between observing a shared state and attempting to modify it, the greater the opportunity for another thread to invalidate that observation. Complex operations can therefore increase the probability that optimistic execution must be abandoned and repeated. This does not imply that all long operations necessarily perform poorly, but it demonstrates that the cost of contention is closely connected to the structure of the algorithm rather than being a fixed property of compare-and-exchange itself.</p><p>Various lock-free algorithms use techniques intended to reduce aggressive retry behavior, including retry backoff and designs that reduce the number of threads modifying a single shared location. Such techniques reveal an interesting characteristic of non-blocking synchronization: although the objective is to avoid blocking dependencies, unrestricted competition for shared state is not necessarily desirable. Efficient implementations often need to control how aggressively threads compete for atomic state while preserving the required progress guarantees.</p><p>At the software level, these effects appear as failed operations, repeated computations, and retry loops. At the hardware level, however, the same contention has another consequence. Atomic modifications performed by different cores must interact with the processor’s cache-coherence system. A shared variable is therefore not merely a logical synchronization point; it can also become a physical communication point between processor cores.</p><p>This hardware dimension is essential because a thread modifying an atomic variable is rarely interacting directly with main memory in isolation. Modern processors rely on multiple levels of cache, and the cache line containing the shared state may be represented in several parts of the memory hierarchy. Coordinating concurrent modifications consequently requires the processor to maintain coherence between these cached copies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kbg5PBuKgZ32_rS_WqN5iw.png" /></figure><h3>Cache Coherence and Shared-State Communication</h3><p>Modern multicore processors rely heavily on caches to reduce the latency associated with accessing main memory. Each processor core typically operates with one or more private cache levels, while additional cache levels may be shared between groups of cores or across the processor. This organization allows frequently accessed data to remain close to the execution units that use it, substantially improving performance for workloads with favorable locality.</p><p>Concurrency complicates this model. When multiple cores access the same memory location, the processor must ensure that their observations remain consistent with the guarantees provided by the architecture. This requirement is handled through cache-coherence mechanisms that track the state of cache lines and coordinate modifications across cores.</p><p>The relevant unit of communication is generally not an individual variable but a cache line containing a range of adjacent bytes. When a core intends to modify data within a cache line, it must obtain the appropriate coherence permissions for that line. Cached copies held by other cores may need to be invalidated or otherwise transitioned to states that prevent conflicting modifications. The exact implementation depends on the processor architecture and coherence protocol, but the general consequence is the same: modification of shared data can require communication beyond the core executing the instruction.</p><p>This behavior is particularly relevant to lock-free algorithms because frequently modified atomic variables often represent synchronization points shared by multiple threads. If different cores repeatedly perform atomic read-modify-write operations on the same cache line, ownership of that line may effectively move between cores as they compete to update it. The resulting communication is sometimes described as cache-line bouncing.</p><p>The important point is that the synchronization cost has not disappeared merely because no operating-system mutex is involved. Part of that cost has moved into the memory hierarchy. A source-level operation that appears to modify a single atomic pointer may trigger coherence activity involving multiple cores. As the frequency of competing modifications increases, this communication can become increasingly significant.</p><p>This explains why the cost of an atomic operation is context dependent. An atomic variable that is rarely modified by competing cores may impose relatively little coherence pressure. The same operation on a highly contended shared variable can behave very differently because each modification interacts with the ownership and visibility of the corresponding cache line. Consequently, reasoning about atomic operations solely in terms of instruction count provides an incomplete picture of their performance characteristics.</p><p>Cache coherence also introduces a problem that does not require threads to access the same logical variable. Two independent variables may occupy the same cache line. If different cores repeatedly modify those variables, coherence mechanisms still operate at cache-line granularity. Each core’s modification can therefore interfere with the other even though the program contains no logical sharing between the variables. This phenomenon is known as false sharing.</p><p>False sharing demonstrates the importance of memory layout in concurrent software. From the perspective of the source code, two counters, indices, or pieces of metadata may be completely independent. From the perspective of the cache hierarchy, however, they may represent a single unit of coherence. Data placement and alignment can therefore influence the performance of concurrent structures independently of their high-level algorithmic design.</p><p>True sharing and false sharing both emphasize a broader principle: communication between threads is ultimately implemented as communication through the memory system. Shared state that appears conceptually inexpensive at the programming-language level may require coordination between physically separate cores. Lock-free programming makes this relationship especially visible because atomic shared state frequently lies directly on the critical execution path.</p><p>Cache coherence should nevertheless not be interpreted as an argument against lock-free algorithms. Coherence traffic is a general consequence of shared-memory concurrency and can also affect lock-based synchronization, since locks themselves typically rely on atomic state and coherent memory. The relevant distinction is therefore not that lock-free algorithms uniquely incur coherence costs, but that their performance can depend heavily on the frequency and distribution of atomic modifications used to coordinate progress.</p><p>This hardware perspective also clarifies why performance characteristics can vary across processor architectures. Different architectures provide different memory models, atomic instruction sets, cache organizations, and coherence implementations. A synchronization strategy that behaves efficiently on one system cannot automatically be assumed to have identical characteristics on another.</p><p>Cache coherence addresses how shared data remains coherent across processors, but coherence alone does not define the ordering relationships that a concurrent program requires. Even when atomicity is guaranteed, threads must still establish which memory operations are allowed to become visible before or after others. This leads to another fundamental component of lock-free design: memory ordering and synchronization semantics.</p><h3>Memory Ordering and Synchronization Semantics</h3><p>Atomicity alone is not sufficient to construct a correct concurrent data structure. An atomic operation guarantees that a particular modification is performed indivisibly with respect to competing operations, but concurrent algorithms often require a stronger property: operations performed by one thread must become observable by another thread in a meaningful and controlled order. This requirement is addressed by the memory model and, in C and C++, by the memory-ordering semantics associated with atomic operations.</p><p>In sequential code, programmers commonly reason about instructions according to the order in which they appear in the source. Concurrent execution makes this model insufficient. Compilers are allowed to reorder operations when doing so preserves the observable behavior of a single thread, and modern processors may execute or expose memory operations in ways that differ from a simple source-order interpretation. Such transformations are essential for performance, but they mean that one thread cannot generally assume that another thread observes independent memory operations in the same order in which they were written.</p><p>Consider a producer that initializes an object and subsequently publishes a pointer to that object through an atomic variable. A consumer may observe the published pointer and then access the object’s contents. Correctness requires more than making the pointer update atomic. The initialization of the object must also become visible to the consumer before the consumer begins using the published object. Without an appropriate synchronization relationship, atomic publication of the pointer alone does not necessarily establish the ordering required for the surrounding non-atomic memory accesses.</p><p>Acquire and release semantics are commonly used to express this relationship. A release operation can publish the effects of preceding operations, while a corresponding acquire operation can ensure that those effects are observed before subsequent operations proceed in the acquiring thread. When correctly paired through the rules of the memory model, these operations establish a synchronization relationship that allows information to move safely between threads without requiring all memory operations to obey a single global ordering.</p><p>This distinction is important because different atomic operations may require different ordering guarantees. Some operations exist primarily to maintain an atomic counter or index and do not publish other memory state. Others represent critical synchronization points through which ownership, initialization, or structural changes become visible to other threads. Applying the strongest ordering everywhere can simplify reasoning in some cases, but it may also impose constraints that the algorithm does not actually require.</p><p>Sequential consistency provides the strongest commonly used ordering model for C and C++ atomics. It offers programmers a relatively intuitive global ordering of sequentially consistent atomic operations and can therefore make concurrent behavior easier to reason about. Weaker orderings, such as acquire, release, or relaxed operations, permit greater flexibility while preserving only the relationships explicitly required by the algorithm. Relaxed atomics still guarantee atomicity for the object involved, but they do not by themselves establish the synchronization relationships necessary to publish arbitrary surrounding memory accesses.</p><p>The choice between these orderings should not be understood simply as selecting between a slow and a fast mode. The relationship between memory ordering and performance is architecture dependent. Some processors naturally provide relatively strong ordering for particular classes of memory operations, while others require additional instructions or barriers to enforce equivalent constraints. Compilers must translate the language-level memory model into operations that satisfy those guarantees on the target architecture. The same C++ memory order can therefore have different implementation consequences on different processors.</p><p>This architecture dependence is particularly relevant when lock-free code is expected to remain portable. A synchronization pattern that appears to work on one machine may contain a latent correctness error that becomes visible on an architecture with weaker memory ordering. Successful execution during testing does not establish that the ordering is valid according to the language memory model. Correctness must instead follow from explicitly defined synchronization relationships.</p><p>At the same time, unnecessarily strong ordering can restrict the implementation more than the algorithm requires. Lock-free programming therefore introduces a difficult engineering balance. Memory ordering must be strong enough to establish all relationships required for correctness, but weakening those guarantees safely requires a precise understanding of which operations communicate state and which ordering relationships the algorithm depends upon.</p><p>This makes memory ordering different from many conventional optimization problems. An incorrect optimization may not simply make a program slower or produce an immediately reproducible failure. It can introduce concurrency defects whose manifestation depends on timing, compiler transformations, processor architecture, and the relative execution of multiple threads. Such defects can remain dormant for long periods and appear only under particular execution conditions.</p><p>For this reason, memory-order selection should follow the correctness argument of the algorithm rather than being treated as an isolated performance tuning technique. The first question is not which memory order is cheapest, but which synchronization relationship is required. Only after that relationship is established can weaker semantics be considered where the algorithm permits them.</p><p>Memory ordering therefore represents another form of cost introduced by non-blocking synchronization. Lock-free algorithms avoid conventional mutual exclusion, but they must explicitly encode the visibility and ordering relationships that allow independently executing threads to cooperate correctly. The resulting complexity is not merely syntactic. It reflects the fundamental problem of establishing causality between operations performed on separate processor cores.</p><p>For dynamically allocated lock-free data structures, however, establishing correct visibility is still not enough. Even when all threads observe structural updates in a valid order, an additional question remains: when can memory that has been removed from the structure actually be reused or released? This question leads to one of the most difficult aspects of practical lock-free design.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*bzy6vtC4bIIRCDEQ4Ows_A.png" /></figure><h3>Safe Memory Reclamation</h3><p>Memory reclamation is a fundamental challenge in lock-free data structures that use dynamically allocated nodes. In a sequential structure, removing an element and reclaiming its storage are often closely related operations. Once a node has been disconnected from a linked structure and no local reference remains, its memory can usually be released. Concurrent execution breaks this simple relationship because another thread may have obtained a reference to the node before it was removed.</p><p>Consider a thread traversing a linked structure. It reads a pointer to a node and intends to inspect the node’s contents or follow its next pointer. Before that access occurs, another thread may successfully remove the same node from the shared structure. From the perspective of the abstract data structure, the removal is complete. The node is no longer reachable through the shared links. Nevertheless, the first thread may still hold the pointer it obtained earlier.</p><p>If the removing thread immediately returns the node’s storage to the allocator, the first thread can subsequently dereference memory whose lifetime has ended. The result is a use-after-free error. More subtly, the allocator may reuse the same address for another object before the first thread accesses it again. In that case, the pointer may still refer to a valid address while no longer referring to the same logical object.</p><p>This leads to an essential distinction between logical removal and physical reclamation. Logical removal determines when an element ceases to belong to the abstract data structure. Physical reclamation determines when the storage previously occupied by that element can safely be reused. In concurrent lock-free structures, these events may need to occur at substantially different times.</p><p>A conventional lock can simplify this problem because the lock can protect both structural access and object lifetime. If every thread that might access a node must hold the same lock, a node can often be reclaimed after it has been removed while exclusive ownership is maintained. Lock-free structures deliberately avoid relying on such global mutual exclusion, so they require another mechanism for determining whether concurrent readers may still possess references to retired objects.</p><p>This requirement has produced several families of safe memory-reclamation techniques. Hazard pointers allow threads to explicitly announce references that they may dereference. Before reclaiming a retired object, the reclamation mechanism checks whether the object is currently protected by another thread. Epoch-based approaches address the problem differently by dividing execution into logical periods and delaying reclamation until it can be established that threads capable of observing older objects have advanced beyond the relevant epoch. Other techniques use quiescent states, reference management, or combinations of these ideas.</p><p>These approaches differ substantially in their mechanisms, but they share a common property: safe reclamation requires information beyond the abstract remove operation itself. The system must somehow reason about references that may exist in concurrently executing threads. Maintaining this information introduces additional state and additional work.</p><p>With hazard pointers, threads must publish and clear protected references, and retired objects generally cannot be reclaimed until the relevant hazard information has been examined. With epoch-based techniques, threads participate in epoch tracking, and retired objects may remain allocated until sufficiently old readers can no longer access them. The resulting costs can include atomic operations, metadata updates, scanning, additional memory retention, and periodic reclamation work.</p><p>The timing of this work is also significant. Reclamation performed aggressively may increase the amount of bookkeeping on frequently executed paths. Delaying reclamation can reduce how often this work occurs, but it may increase the amount of memory occupied by retired objects. Safe memory reclamation therefore introduces its own balance between synchronization overhead, reclamation latency, memory consumption, and implementation complexity.</p><p>This issue demonstrates why the complexity of a practical lock-free structure can extend well beyond its core algorithm. A queue or stack may have a conceptually compact atomic update sequence, yet a complete implementation must also solve the lifetime problem for objects that concurrent threads can observe. Evaluating only the successful atomic transition therefore omits an important part of the system required to make that transition safe in a reusable implementation.</p><p>Memory reclamation also interacts with the memory-ordering concerns discussed previously. Publishing protected references, observing thread states, and determining when reclamation is safe all require carefully defined synchronization relationships. A reclamation scheme is therefore not an independent layer that can simply be attached to an otherwise complete lock-free algorithm. Its correctness depends on the same atomic and visibility mechanisms that govern the data structure itself.</p><p>Another well-known difficulty is the ABA problem. Suppose a thread reads a shared value A and is temporarily delayed. Another thread changes the value from A to B and later changes it back to A. When the first thread resumes, a compare-and-exchange that checks only the current value may observe A and conclude that the state has not changed, even though an intermediate modification occurred. When the value represents a pointer, memory reclamation and address reuse can make this scenario particularly significant because a newly allocated object may occupy an address previously associated with a different logical object.</p><p>Solutions to ABA can involve tagged or versioned values, reclamation strategies that prevent premature reuse, or algorithm-specific techniques. Once again, solving the problem introduces state or constraints beyond the abstract data-structure operation. This reinforces a recurring theme in lock-free design: correctness properties that appear simple at the algorithmic level may depend on substantial supporting mechanisms when implemented on real shared-memory systems.</p><p>Safe reclamation therefore represents more than a memory-management detail. It is part of the synchronization design of a dynamically allocated lock-free data structure. The cost of an implementation cannot be understood solely through the atomic operations that update its head, tail, or links; it must also include the mechanisms that make the lifetime of those objects safe under concurrent access.</p><p>Taken together, atomic synchronization, contention, cache coherence, memory ordering, and reclamation reveal a common pattern. Removing locks does not remove coordination from a concurrent system. Instead, coordination becomes distributed across the algorithm, the language memory model, the memory-management strategy, and the hardware responsible for maintaining coherent shared memory.</p><h3>Conclusion</h3><p>Lock-free data structures represent an important approach to concurrent programming because they provide progress guarantees without making system-wide progress depend on ownership of a conventional lock. Their significance, however, should not be reduced to the assumption that avoiding locks inherently produces faster execution. Lock-freedom defines how progress is maintained under concurrency; it does not define the cost at which that progress is achieved.</p><p>Replacing mutual exclusion with non-blocking synchronization changes the form of coordination rather than eliminating it. Atomic read-modify-write operations provide the mechanisms required to modify shared state safely, but competing updates can fail and require retries. Under contention, these retries may increase the amount of executed work without producing a corresponding increase in completed operations. At the hardware level, modifications to shared state interact with cache-coherence mechanisms, making communication between cores part of the effective cost of synchronization.</p><p>Memory ordering adds another dimension to this problem. Correct concurrent execution requires not only atomic state transitions but also carefully defined visibility relationships between operations performed by different threads. These relationships must be expressed through the language memory model and ultimately implemented by the compiler and processor architecture. Choosing appropriate ordering semantics is therefore a correctness requirement first and a performance consideration second.</p><p>For dynamically allocated structures, safe memory reclamation extends the synchronization problem beyond the moment at which an element is logically removed. A node may cease to belong to a data structure while remaining accessible to another concurrent thread. Techniques such as hazard pointers and epoch-based reclamation address this lifetime problem, but they necessarily introduce additional metadata, synchronization, delayed reclamation, or bookkeeping.</p><p>The resulting picture is more nuanced than a simple comparison between locks and atomics. Lock-based and lock-free designs represent different strategies for coordinating concurrent access, and each strategy places costs in different parts of the system. In lock-free structures, some of those costs become visible as retry behavior, atomic synchronization, coherence communication, ordering constraints, and reclamation complexity.</p><p>A more precise understanding of lock-free performance therefore begins by separating progress guarantees from performance guarantees. The absence of locks is an algorithmic property, not a measure of efficiency. The practical behavior of a lock-free data structure emerges from the interaction between its algorithm, the programming-language memory model, memory-management strategy, and the underlying processor architecture.</p><p>For this reason, lock-free design is best understood not as the elimination of synchronization, but as a redistribution of synchronization responsibilities across multiple layers of the system. That distinction is essential both for reasoning correctly about non-blocking algorithms and for understanding the performance trade-offs that accompany them.</p><h3>References</h3><p>[1] M. Herlihy and J. M. Wing, “Linearizability: A Correctness Condition for Concurrent Objects,” ACM Transactions on Programming Languages and Systems, vol. 12, no. 3, pp. 463–492, 1990. doi: 10.1145/78969.78972. <a href="https://www.cs.cmu.edu/~wing/publications/HerlihyWing90.pdf?utm_source=chatgpt.com">CMU School of Computer Science</a></p><p>[2] M. M. Michael, “Hazard Pointers: Safe Memory Reclamation for Lock-Free Objects,” IEEE Transactions on Parallel and Distributed Systems, 2004. This is particularly relevant to the article’s discussion of safe reclamation, retired nodes, and the ABA problem. <a href="https://research.ibm.com/publications/hazard-pointers-safe-memory-reclamation-for-lock-free-objects?utm_source=chatgpt.com">IBM Research</a></p><p>[3] Intel Corporation, Intel 64 and IA-32 Architectures Optimization Reference Manual. The manual discusses multicore performance, sharing of modified data, cache coherence, and false sharing, making it particularly relevant to the cache-coherence section. <a href="https://www.intel.com/content/dam/doc/manual/64-ia-32-architectures-optimization-manual.pdf?utm_source=chatgpt.com">Intel</a></p><p>[4] cppreference, “std::memory_order — C++ Atomic Operations Library.” A practical reference for relaxed, acquire, release, acquire-release, and sequentially consistent memory ordering, including the release-acquire synchronizes-with relationship discussed in this article. <a href="https://en.cppreference.com/cpp/atomic/memory_order?utm_source=chatgpt.com">Cppreference</a></p><p>[5] cppreference, “std::atomic — C++ Atomic Operations Library.” Reference documentation covering atomic load, store, and read-modify-write operations and their relationship with inter-thread synchronization. <a href="https://www.cppreference.com/cpp/atomic/atomic?utm_source=chatgpt.com">Cppreference</a></p><p>[6] cppreference, “C Memory Model.” Reference material covering data races, atomic operations, happens-before relationships, and the C11 memory model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43104d77611c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Reduced an Embedded Linux Boot Time from 35 Seconds to Under 10 Seconds]]></title>
            <link>https://medium.com/@seldaturgut2020/how-i-reduced-an-embedded-linux-boot-time-from-35-seconds-to-under-10-seconds-9301d50223ab?source=rss-4bef563f249e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9301d50223ab</guid>
            <category><![CDATA[boot-optimization]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[systemd-service]]></category>
            <category><![CDATA[yoctoproject]]></category>
            <dc:creator><![CDATA[Selda Turgut]]></dc:creator>
            <pubDate>Thu, 03 Sep 2026 08:50:58 GMT</pubDate>
            <atom:updated>2026-09-03T08:50:58.155Z</atom:updated>
            <content:encoded><![CDATA[<p>An engineering case study on measuring the critical boot path, restructuring systemd services, and removing unnecessary delays in a Yocto-based embedded Linux system.</p><p>Boot time can easily become an afterthought in embedded Linux projects. During development, new services, initialization scripts, hardware checks, and temporary workarounds are gradually added to the system. Each addition may look harmless on its own, but together they can turn startup into a long chain of unnecessary waits.</p><p>I encountered exactly this problem while working on a Yocto-based embedded Linux device. The system took approximately 35 seconds to become operational after power-on. This was too slow for a device expected to initialize its communication interfaces and application services shortly after receiving power.</p><p>The first instinct might be to disable anything that appears slow. However, embedded systems often depend on hardware initialization, device nodes, network interfaces, and service ordering. Removing the wrong dependency can make the system appear faster while introducing intermittent failures.</p><p>Instead, I approached the problem as a critical-path analysis: measure the startup sequence, identify what was actually blocking progress, and shorten that path without removing required functionality.</p><p>The result was a reduction from approximately 35 seconds to under 10 seconds.</p><h3>The Initial Problem</h3><p>The target was an ARM-based embedded Linux device running a custom Yocto image and using systemd as its init system. During startup, the device had to initialize several hardware and software components, including:</p><ul><li>CAN interfaces</li><li>A cellular modem</li><li>A wireless network interface</li><li>USB networking</li><li>Device-specific application services</li></ul><p>Although all these components were necessary, they did not all need to start sequentially. Over time, some initialization steps had been placed inside a legacy rc.local script, while others were implemented as separate systemd services with broad or unnecessary dependencies.</p><p>This created three main problems:</p><ol><li>Some independent operations were executed one after another.</li><li>Hardware-related waits blocked services that did not depend on that hardware.</li><li>The difference between “Linux has started” and “the device is operational” was not clearly defined.</li></ol><p>The kernel itself was not responsible for the entire delay. A significant portion of the boot time came from userspace initialization and the way services were ordered.</p><p>Before changing anything, I needed to answer a more important question:</p><p><strong>What exactly did “boot complete” mean for this device?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Y-9nxn1GHd0Se12dFTNTA.png" /></figure><h3>Defining “Boot Complete”</h3><p>Before starting the optimization, I needed a clear definition of when the boot process was actually complete. A short kernel startup time does not necessarily mean that an embedded device is ready to perform its intended function. The kernel may finish booting while network interfaces, communication buses, device nodes, or the main application are still unavailable. For this project, I considered the device operational only when the kernel and userspace initialization had completed, the required CAN and network interfaces were available, and the main application services had started successfully. The goal was therefore not simply to reach a login prompt faster, but to make the complete device ready for use as quickly and reliably as possible.</p><p>This definition also prevented misleading improvements. Disabling a slow service could reduce the time reported by systemd, but it would not be a real optimization if an essential interface or application became unavailable afterward. Every change therefore had to satisfy two conditions: it had to shorten the actual startup path, and the device still had to provide the same required functionality after boot.</p><h3>Measuring the Baseline</h3><p>I began by collecting a baseline before changing any service or configuration. Running systemd-analyze separated the startup duration into kernel and userspace time, while systemd-analyze blame showed which services and device units spent the most time initializing. The initial results pointed to several notable delays: the legacy rc.local initialization took approximately 6.2 seconds, a filesystem device wait took around 3.8 seconds, random-seed initialization varied between 1.8 and 4.6 seconds, RF-kill initialization took about 2 seconds, the cellular modem power service took approximately 1.7 seconds, and udev device triggering added around 1.4 seconds.</p><pre>systemd-analyze<br>systemd-analyze blame</pre><p>The blame output provided a useful starting point, but it could not be treated as a list of delays that could simply be added together. Multiple systemd units may run in parallel, so a service taking two seconds does not necessarily increase the total boot time by two seconds. A slow unit matters only when another required unit is waiting for it or when it belongs to the critical path. To understand these relationships, I used systemd-analyze critical-chain, which revealed the dependency sequence that was actually delaying the boot target. I also examined the logs with monotonic timestamps using journalctl -b -o short-monotonic. This made it easier to follow the order of events and see how much time had elapsed since power-on without depending on the device’s wall-clock configuration.</p><pre>systemd-analyze critical-chain<br>journalctl -b -o short-monotonic</pre><p>The measurements showed that the problem was not caused by a single unusually slow component. It resulted from a combination of legacy initialization logic, unnecessary service ordering, hardware-related waits, and independent operations being executed sequentially. This changed the direction of the work: instead of focusing only on individual service durations, I began examining how the complete startup sequence was structured.</p><h3>Finding the Real Bottlenecks</h3><p>The largest visible delay came from rc-local.service, which took approximately 6.2 seconds. The script had gradually become responsible for several unrelated initialization tasks, including network configuration, hardware setup, and application-specific operations. Because the commands were executed sequentially, a slow hardware initialization step delayed everything that followed it, even when the later operations did not depend on that hardware. This made the script convenient during early development but inefficient as part of the final boot sequence. It also made failures difficult to isolate because systemd could only report the total execution time of rc.local, rather than tracking each operation as an individual service.</p><p>Other delays required more careful investigation. For example, the cellular modem needed time to power up and expose its device interfaces, while CAN and USB networking had their own initialization requirements. These operations were necessary, but they did not all depend on one another. Some services also used broad ordering rules or waited for general system targets when they only required a specific device or interface. As a result, independent tasks were unnecessarily serialized. The filesystem device wait, random-seed initialization, RF-kill handling, and udev processing also appeared in the measurements, but their presence in systemd-analyze blame did not automatically mean they were safe to remove. Each one had to be checked against the critical chain and the actual runtime requirements of the device.</p><h3>Replacing rc.local with Dedicated Services</h3><p>The most important structural change was moving initialization logic out of rc.local and into dedicated systemd services. Instead of treating the entire device setup as one long script, I separated USB networking, wireless networking, cellular modem power, CAN configuration, and application startup into individual units. This allowed systemd to manage each operation independently, start unrelated tasks in parallel, record their execution times separately, and restart a failed component without repeating the complete initialization sequence.</p><p>Each service was then given only the dependencies it actually required. A hardware-dependent service could wait for its corresponding device node or interface, while an unrelated network or application service could continue starting in parallel. This reduced unnecessary serialization and made the startup sequence easier to understand. It also improved maintainability: when one component failed, its status and logs could be inspected directly with systemctl status and journalctl -u, rather than searching through the output of a large initialization script.</p><p>A simplified service structure looked like this:</p><pre>[Unit]<br>Description=Configure USB network interface<br>After=sys-subsystem-net-devices-usb0.device<br>BindsTo=sys-subsystem-net-devices-usb0.device<br>[Service]<br>Type=oneshot<br>ExecStart=/usr/bin/configure-usb-network<br>RemainAfterExit=yes<br>[Install]<br>WantedBy=multi-user.target</pre><p>This example illustrates the main idea rather than the exact production configuration. The service waits for the specific usb0 interface it needs instead of delaying unrelated parts of the boot process behind a general initialization script. Applying the same principle to the other components transformed the startup sequence from a mostly sequential chain into a set of smaller services that systemd could schedule according to their real dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jdBodfJYtWZEMIXP3oohhA.png" /></figure><h3>Optimizing Service Dependencies and Hardware Waits</h3><p>After splitting the initialization tasks into separate services, the next step was to review how those services depended on devices, interfaces, and systemd targets. Some units were waiting for broad targets even though they only required a particular interface or device node. This introduced delays because a service could remain blocked by unrelated initialization work. I replaced these broad dependencies with more specific relationships wherever possible, allowing systemd to start independent services in parallel while still preserving the required startup order.</p><p>Hardware availability was especially important for the cellular modem, CAN interfaces, and GNSS device. These components do not necessarily become available at the same moment during every boot, so replacing every wait with a fixed delay would only make the sequence fragile. Instead, hardware-dependent services were connected to the device or interface they actually required. Udev rules were used to provide stable device naming where necessary, and CAN configuration was started only after the relevant device initialization had completed. This reduced unnecessary waiting without creating a race condition between hardware discovery and application startup.</p><p>The cellular modem was handled separately because it required a power-up sequence before its interfaces became available. Rather than blocking the complete initialization flow, modem power control was moved into its own service. Other components that did not depend on the modem could continue starting while it initialized. The same principle was applied to USB and wireless networking: each service was responsible for one component, declared only its real dependencies, and could be diagnosed independently if startup failed.</p><h3>Additional System-Level Improvements</h3><p>Once the service structure was improved, I examined smaller delays in the remaining boot path. Persistent logging, filesystem behavior, random-seed initialization, RF-kill handling, and filesystem checks all affected startup time to some degree. These were not treated as services that could simply be disabled. Each one was evaluated according to the device’s actual requirements and failure model. For example, reducing persistent writes may be reasonable for an embedded device that sends important logs to another system, but it would be a poor decision if local logs were the only way to investigate field failures.</p><p>For this system, journald was configured to use volatile storage, reducing unnecessary writes during startup. The root filesystem mount configuration was also reviewed, and options such as noatime and nodiratime were used to avoid metadata writes caused only by file access. Filesystem checks were removed from the normal boot path only where the storage design and recovery strategy made that acceptable. These changes provided smaller improvements than restructuring rc.local, but together they helped shorten the remaining userspace initialization time.</p><p>Random-seed initialization and RF-kill handling required similar care. A delay shown by systemd-analyze blame was not sufficient justification for disabling either component. Removing random-seed initialization without understanding how the device uses randomness could weaken security, while disabling RF-kill handling could affect wireless state management. The final configuration was based on the hardware and software requirements of the target image rather than applying generic boot-optimization recommendations blindly.</p><h3>The Final Results</h3><p>After restructuring the initialization process and refining the remaining system configuration, the measured startup time fell from approximately 35 seconds to under 10 seconds. In one of the final measurements, the kernel completed in 2.541 seconds and userspace initialization completed in 7.271 seconds, giving a total reported time of approximately 9.813 seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F8O7cKTOGbogsbb9RgF53g.png" /></figure><p>This corresponds to a reduction of roughly 72% compared with the initial startup time. More importantly, the result was achieved without removing the communication interfaces and application services required by the device. CAN, USB networking, wireless networking, modem initialization, and the main application remained part of the startup process. The improvement came primarily from shortening the critical path, allowing independent work to run in parallel, and eliminating unnecessary serialization.</p><p>The final number was not treated as the result of a single successful boot. The device was restarted repeatedly, and the required interfaces and services were checked after startup. Hardware initialization time can vary slightly between boots, particularly when modems and network interfaces are involved. The goal was not to produce the smallest possible number once, but to achieve a consistently faster and still reliable startup sequence.</p><h3>What I Learned</h3><p>The most important lesson from this work was that embedded Linux boot optimization is not mainly about disabling services. It is about understanding the critical path. systemd-analyze blame is useful for discovering slow units, but it does not show the complete relationship between them. A service with a long execution time may have little impact if it runs in parallel, while a shorter service can become a major bottleneck if several required components are waiting for it. Combining timing measurements, dependency analysis, and boot logs provided a much more accurate picture of the system.</p><p>I also learned that service architecture has a direct effect on both performance and maintainability. Moving unrelated operations out of rc.local did more than reduce boot time. It made each initialization step observable, independently restartable, and easier to debug. Explicit dependencies replaced assumptions hidden inside shell scripts, while hardware-specific waits became localized to the services that actually needed them.</p><p>Finally, every optimization had to be evaluated as an engineering trade-off. Disabling a filesystem check, changing logging behavior, or removing a hardware wait may improve a timing result, but it can also reduce reliability, security, or diagnostic capability. The objective was therefore not simply to boot as fast as possible, but to create the shortest reliable path from power-on to an operational embedded system.</p><p>Reducing the startup time from approximately 35 seconds to under 10 seconds was the visible outcome, but the more valuable result was a cleaner, more predictable, and more maintainable boot process.</p><h3>References</h3><ul><li>systemd, <a href="https://www.freedesktop.org/software/systemd/man/latest/systemd-analyze.html"><em>systemd-analyze — Analyze and Debug System Manager</em></a>. Documentation for measuring boot performance and inspecting the critical startup path.</li><li>systemd, <a href="https://www.freedesktop.org/software/systemd/man/latest/systemd.unit.html"><em>systemd.unit — Unit Configuration</em></a>. Reference for unit dependencies and ordering directives such as After=, Before=, Requires=, and Wants=.</li><li>systemd, <a href="https://www.freedesktop.org/software/systemd/man/latest/systemd.device.html"><em>systemd.device — Device Unit Configuration</em></a>. Documentation for representing kernel devices as systemd units and connecting services to hardware availability.</li><li>systemd, <a href="https://www.freedesktop.org/software/systemd/man/latest/journald.conf.html"><em>journald.conf — Journal Service Configuration</em></a>. Reference for journal storage modes, including Storage=volatile.</li><li>Yocto Project, <a href="https://docs.yoctoproject.org/current/ref-manual/classes.html#systemd"><em>Reference Manual: systemd Class</em></a>. Documentation for installing, packaging, and enabling systemd service files in Yocto recipes.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9301d50223ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can LLMs Estimate Execution Time from C Source Code?]]></title>
            <link>https://medium.com/@seldaturgut2020/can-llms-estimate-execution-time-from-c-source-code-24f5e5e455d8?source=rss-4bef563f249e------2</link>
            <guid isPermaLink="false">https://medium.com/p/24f5e5e455d8</guid>
            <category><![CDATA[wcet]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[scheduling-software]]></category>
            <category><![CDATA[real-time-systems]]></category>
            <dc:creator><![CDATA[Selda Turgut]]></dc:creator>
            <pubDate>Fri, 28 Aug 2026 18:23:32 GMT</pubDate>
            <atom:updated>2026-08-28T18:23:32.470Z</atom:updated>
            <content:encoded><![CDATA[<p>Exploring source-level timing estimation for real-time embedded systems</p><h3>Source-Level Execution-Time Estimation: The Information Gap</h3><p>Execution time is a fundamental design constraint in real-time embedded systems, where the correctness of a software component depends not only on the result it produces but also on whether that result is delivered within the required time. Obtaining reliable timing information, however, generally requires artifacts and platform knowledge that become available only after the software has progressed beyond its source-level representation. Measurement-based approaches require an executable program and access to the target hardware, while more rigorous timing-analysis techniques typically operate on compiled code and rely on architectural information about the processor and memory system.</p><p>This creates a relevant information gap during earlier stages of development. At this point, the C source code may already describe the computational structure of a task in considerable detail, including loops, conditional branches, function calls, and memory operations, while the exact instruction sequence and its execution behavior on the target processor remain unknown. Nevertheless, early timing information can be valuable when evaluating implementation alternatives, identifying potentially expensive code paths, or reasoning about whether a task is likely to satisfy its timing requirements before the complete execution environment is available.</p><p>The emergence of large language models introduces an interesting possibility in this context. Modern LLMs have demonstrated a strong ability to interpret source code and reason about its structure, allowing them to identify control-flow patterns, derive explicit loop bounds, follow function relationships, and characterize operations directly from C. These capabilities raise the possibility of using an LLM to extract timing-relevant information before compilation and, potentially, to derive an early estimate of execution cost.</p><p>The difficulty is that execution time is not determined by source code alone. A C program is transformed by the compiler into a sequence of machine instructions whose structure depends on factors such as the target architecture, compiler configuration, optimization strategy, and register allocation. The resulting instructions are then executed within a hardware environment whose memory organization and processor characteristics further influence timing. Consequently, two source-level constructs that appear computationally similar do not necessarily correspond to the same execution cost at machine level.</p><p>The central question is therefore not simply whether an LLM can generate a numerical execution-time prediction. Producing such a number is relatively straightforward. The more meaningful question is whether the timing-relevant properties available at source level contain enough information for that prediction to be technically justified, and how the uncertainty introduced by the missing compilation and hardware layers should be represented.</p><p>This distinction forms the basis of the approach explored in this work: rather than treating source-level execution-time estimation as a direct mapping from C code to processor cycles, the problem is considered as an analysis of what timing information can be inferred from the source, what additional information must be supplied about the target platform, and what remains unresolved until later stages of the compilation and execution process.</p><h3><strong>LLM-Assisted Analysis of Embedded C</strong></h3><p>To investigate this problem, I approached the LLM not simply as a predictor of execution time, but as a source-level analysis component. Instead of asking the model to directly guess how many cycles a function would require, the analysis was structured around timing-relevant properties that can be identified from C code. These included execution paths, loop bounds, direct function calls, repeated operations, and information that could not be resolved statically.</p><p>The source code was analyzed together with a description of the target hardware and compilation environment. An important constraint was that the model was not allowed to silently invent missing loop bounds or hardware costs; information that could not be justified from the available context had to remain explicitly unresolved. The output was also structured rather than free-form, allowing the reasoning behind the estimate to remain inspectable.</p><p>To provide additional context, I explored retrieval-augmented generation using previously measured C tasks as reference examples. Similar examples could therefore support the analysis without exposing the model to the task being evaluated itself. This required separating reference data from evaluation inputs and filtering identical or near-duplicate tasks to reduce information leakage.</p><p>The resulting pipeline combined three different sources of information: what could be inferred directly from the C source, what was explicitly known about the execution platform, and what could be learned from relevant historical examples. The objective was not only to obtain an execution-time estimate, but to understand how much of that estimate could be traced back to evidence available before compilation.</p><h3>Limitations of Direct Cycle Prediction</h3><p>The structured analysis made the reasoning process more transparent, but it did not eliminate the fundamental uncertainty between source code and processor execution. In particular, the quality of a timing estimate depended not only on whether the model understood the C code correctly, but also on whether the information required to translate that understanding into processor cycles was actually available.</p><p>One difficulty is the compiler boundary. Source-level operations do not map directly to individual machine instructions, and their cost cannot be determined reliably by counting C constructs alone. Instruction selection, register allocation, memory accesses, and optimization decisions are introduced during compilation. Even when the compiler and optimization settings are known, predicting their exact effect without inspecting the generated code remains an approximation.</p><p>A second difficulty concerns the hardware model. Providing the target architecture and compilation profile gives the LLM useful context, but incomplete timing information creates an important failure mode: the model may replace missing information with technically plausible assumptions. An assumed memory penalty or processor cost can make an estimate appear more conservative without making it more defensible. In timing analysis, this distinction is critical because an unsupported assumption does not become reliable simply by increasing the predicted execution time.</p><p>This also limits the usefulness of applying a fixed safety margin to the final prediction. Such a margin may increase the numerical estimate, but it does not address the reason the original estimate was uncertain. Errors originating from unresolved loop behavior, compiler transformations, memory effects, or incomplete hardware information have different causes and cannot necessarily be represented by a single correction factor.</p><p>These observations suggest that the main limitation is not the LLM’s ability to produce a cycle estimate. It is the difficulty of determining which parts of that estimate originate from observable program structure and which depend on assumptions about information that is unavailable at source level. For execution-time analysis, maintaining this distinction may be more important than producing a more precise-looking number.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u7KMBw1yJsmbORhqz8Lq4Q.png" /></figure><h3>Toward Hybrid LLM-Based Timing Analysis</h3><p>The limitations of direct cycle prediction do not necessarily imply that LLMs have no role in execution-time analysis. Instead, they suggest that the model’s responsibility within the analysis pipeline may need to be reconsidered.</p><p>The strongest part of source-level LLM analysis is its ability to reason about program structure. Execution paths, explicit loop bounds, function relationships, repeated operations, and unresolved dependencies can often be identified directly from C code. These properties are relevant to timing analysis, but they are fundamentally different from the hardware costs eventually assigned to them.</p><p>A more robust direction would therefore be to separate these responsibilities. Rather than asking the LLM to infer both program behavior and its final cycle cost, the model could focus on extracting timing-relevant properties into a structured representation. Hardware-specific costs and numerical timing calculations could then be handled by a deterministic component whose assumptions are explicitly defined and independently verifiable.</p><p>Such a separation would also make uncertainty easier to preserve. If a loop bound cannot be established from the source, it can remain unresolved. If the cost of a memory access is not available in the hardware model, the analysis does not need to invent one. The objective shifts from forcing the system to always produce a number toward producing an estimate only from information that can be traced to an explicit source.</p><p>This does not turn an LLM-based system into a WCET analyzer, nor does it remove the need for compilation, hardware-aware analysis, or target measurements. Instead, it positions the LLM earlier in the timing-analysis workflow, where semantic reasoning over source code may provide useful information before lower-level artifacts become available.</p><p>From this perspective, the more interesting research question is no longer simply whether an LLM can predict processor cycles from C. It is whether an LLM can reliably extract enough timing-relevant structure to become a useful component of a larger, evidence-driven execution-time analysis pipeline.</p><h3>Conclusion</h3><p>Estimating execution time directly from C source code is an attractive idea, particularly in real-time embedded development where timing information can influence architectural decisions long before the final executable is available. LLMs make this possibility especially interesting because they can reason about source-level properties such as control flow, loop bounds, function relationships, and repeated operations without requiring the program to be executed.</p><p>However, source-level understanding and processor-level timing are not the same problem. Compilation introduces transformations that are not fully represented in the original C code, while the target architecture introduces execution costs that cannot always be inferred from source structure alone. Providing additional hardware context or retrieved examples can reduce this information gap, but it does not eliminate it.</p><p>This suggests a more useful role for LLMs in timing analysis: not necessarily as timing oracles that directly map C code to cycle counts, but as source-level reasoning components within a broader analysis pipeline. Future work could extend this idea by incorporating representations such as ASTs or LLVM IR, allowing the model to reason across different levels of program abstraction while keeping hardware-specific timing calculations explicit and verifiable.</p><p>The question, therefore, may be less about whether an LLM can predict execution time from C, and more about where an LLM can contribute reliable information to the execution-time analysis process.</p><h3>References</h3><ul><li>R. Wilhelm et al., “The Worst-Case Execution-Time Problem — Overview of Methods and Survey of Tools,” <em>ACM Transactions on Embedded Computing Systems</em>, vol. 7, no. 3, Article 36, 2008. <a href="https://www.google.com/search?q=https://doi.org/10.1145/1347375.1347389&amp;authuser=1">Paper / DOI</a></li><li>Arm Ltd., <em>Arm Cortex-M4 Processor Technical Reference Manual</em>. Arm Developer Documentation. <a href="https://developer.arm.com/documentation/100166/latest/">Arm Documentation</a></li><li>NXP Semiconductors, <em>S32K1xx MCU Family Reference Manual</em>. NXP Semiconductors, Rev. 14.2, 2026. <a href="https://www.google.com/search?q=https://www.nxp.com/products/processors-and-microcontrollers/arm-microcontrollers/s32k-automotive-mcus/s32k1-microcontrollers-for-automotive-general-purpose:S32K1&amp;authuser=1">NXP S32K1 Documentation</a></li><li>GNU Project, <em>Options That Control Optimization — Using the GNU Compiler Collection</em>. GCC Documentation. <a href="https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html">GCC Optimization Options</a></li><li>LLVM Project, <em>LLVM Language Reference Manual</em>. LLVM Documentation. <a href="https://llvm.org/docs/LangRef.html">LLVM Language Reference</a></li><li>Clang Project, <em>Introduction to the Clang AST</em>. Clang Documentation. <a href="https://clang.llvm.org/docs/IntroductionToTheClangAST.html">Clang AST Documentation</a></li><li>H. Jiang et al., “Can Large Language Models Understand Intermediate Representations in Compilers?” <em>Proceedings of the 42nd International Conference on Machine Learning (ICML)</em>, PMLR 267, pp. 27851–27872, 2025. <a href="https://proceedings.mlr.press/v267/jiang25p.html">ICML / PMLR Paper</a></li><li>B. Rozière et al., “Code Llama: Open Foundation Models for Code,” <em>arXiv:2308.12950</em>, 2023. <a href="https://arxiv.org/abs/2308.12950">arXiv Paper</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24f5e5e455d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>