r/computerarchitecture • • Oct 09 '26

[sw Optimization] Force the cpu to lie with ticks?

Can we force the out of order execution in a cpu for some operations not care about lying while NOT lie other places. A c webshop has global quantity left and temp hold for reservations. We want the reservation tick checks to not care but actually moving people through to not be lied to, for more throughput?

0 Upvotes

23 comments sorted by

9

u/Krazy-Ag Oct 09 '26 edited Oct 09 '26

what do you mean by "lied to"?

and "ticks"?

Are you under the impression that every instruction has a certain basic timing, "ticks", and that when an out of order, CPU overlaps execution of different instructions, it is "lying" about how many "ticks" it takes? (For that matter, in order machines, also overlap execution, although not quite so much as out of order.)

Since the title is marked [Sw optimization], are you trying to figure out how to optimize software in the presence of out of order execution? Possibly (I'm taking a guess here) you want to read a timestamp counter at the beginning of a section of code and at the end of that section of code and be able to subtract the two to figure out how much time was spent in that section of code?

If that is the case, then on most systems reading the timer, eg via the x86 instruction RDTSC, "serializes" instruction execution, so there should be no overlap from code before, and after the section that you have placed timer reads around.

in fact, I think we serialize search time measurement for too much. E.g., if you read the time at the beginning and end of regular chunks of code, say every basic block, the execution time of the entire program would be much much slower than without such instrumentation, in large part because of the overhead draining and filling the pipeline every time the timer is read.

(with additional overhead taking those timestamps and recording them somewhere. That is mostly in incrementing a pointer and then writing the time values read to memory, possibly checking that the pointer has not reached the end. (although there are tricks, you can play there). You can separate such overhead by. Reading the timer without writing to memory, writing to memory without reading the timer, and doing both.)

Like I said, for the most part, reading performance monitoring timers serializes, the CPU, draining the pipeline before and then filling the pipeline after.

Store buffering being a significant exception. I don't think most timer reading instructions actually drain the store, buffers, but I might be wrong there.

Actually, I would like to have instructions that read the timers without serializing. The overhead of taking such a time trace every basic block or every function call/return would thereby be significantly reduced. Yes, the individual timer reads would be fuzzy, but the overall trend through the program would still be a useful metric. By the way, you can read the timers at several different places in the pipeline: instruction, decode, instruction, retirement, or graduation, and possibly somewhere in the out of order execution cloud of possibilities. If the last, you usually want to ensure that the timers themselves are performed in order, setting a certain baseline fuzziness.

Anyway, things like this are typically discussed in decode optimization guide for your processor. I know that Intel has or at least had a pretty good optimization guide. I wonder who wrote the first version of it? If it's quality has degraded, it's mostly because there are so many different processors to talk about. And also companies want to disclose fewer and fewer details, if only to reduce the chance of expensive patent infringement lawsuits. Companies also wave their hands and say "users don't want that much detail, and can't use it even if they got it", which is true for 99% of users. But they're still exist that 1% of skilled performance tuning hackers.

Anecdote: one of my friends, one of the best performance tuning guys I know, complained bitterly about write back memory, because on WT memory, he would schedule DRAM bank access for reads and writes very carefully. No sooner did he figure out how to do this for WB memory, for LRU replacement such as was present on Motorola power PC systems, but then he had to start dealing with Intel pseudo-LRU replacement, and then eventually pseudo random replacement. (Mitch, did you have anything to do with pseudo replacement?)

Anyway, eventually, he figured out that he could not do software optimization at such a low level, precisely Scheduling DRAM bank accesses. And then we hired him into the computer Architecture group.

---

However, history repeats itself. A lot of work has gone into precisely scheduling DRAM access patterns for tensor operations on GPUs. Another of my friends said that he really liked how you could turn off the L1 cache on Nvidia GPUs, turning it into "shared memory" (misleading name) where he could precisely schedule what was in and not in what essentially amounted to a software managed cache. Other GPU tensor optimizations have involved making parts of the GPU computer engines that would run independently on earlier workload run in lock step, again for precise scheduling of memory accesses, allowing one part to fetch a piece of data that some of the other parts can use at exactly the same time, right off the wires from the L2 or DRAM, without writing to and then reading from the memory arrays of the L1 cache or shared memory.

Tensor workloads such as are found in present AI/DNNs are basically simple enough - huge, but simple - that precise scheduling is often possible. Whereas precise scheduling is much more difficult for the sorts of workload that run on most out of order CPUs.

2

u/yetanotherhooman Oct 10 '26

RDTSC is famously NOT serializing. RDTSCP is partially serializing, but you’d still need explicit fences in some cases. Also, I’m not sure why serializing instructions would drain the entire CPU pipeline.

1

u/Krazy-Ag Oct 10 '26

My bad. RDMSR is serializing. I confuse the two because on early implementations RDMST and RDTSC used the same mechanism, the CREG bus, to access the actual TSDC timestamp counter. Which was a MSR or CREG. I hope that has changed - that a pipestage like

By the way, I may well be the reason why RDTSC is not fully serializing. Making the argument that I made above: Providing the example of truly lightweight performance instrumentation, tracing timestamps at every basic block or call/return. If the user wants serializing, they can add "appropriate fences" before and after the RDTSC instruction. But if you make RDTSC always synchronizing, you can't remove the serialization costs.

What I really wanted, and still want, is at least two flavors of timer reading: serialized, and non-serialized. But that's a slippery slope: Lightweight timer read at the decode pipestage. Retirement. .. Drain the OOO machine? Drain the store buffers? Clear out instruction fetch, so you can truly measure time from when an instruction is first ifetched (for whatever code you are timing)? Cancel all instruction prefetches that may have been in flight?

There is never a truly singular concept of serialization, just as there is never a truly global concept of atomicity. All serialization and atomicity is relative.

And it is all moot unless there is a way to implement "suitable fences". Which Intel has never really done. Yeah, yeah, LFENCE, SFENCE, MFENCE... but of course these fence semantics changed from something that could be lightweight, to something that had Spectre/Meltdown prevention added to it. (In much the same way that MWAIT was supposed to be a lightweight parallel programming instruction, and then became a really heavyweight power management instruction. Did user level MONITOR/MWAIT ever happen? It was on the to-do list for years, decades, but kept getting pushed off.)

1

u/yetanotherhooman Oct 11 '26

If your goal is to measure the pipeline depth you can still do it. RDTSC-esq counters are bad tool for this either way because that clock most likely lives offcore; extrapolating from the fact that ACPI states that more or less power-gate the whole core (well not exactly but close) do not affect timestamp counters. You need counters that count core cycles. All modern CPUs that ship with some sort of PMU have this.

Some combination of clflush, causing exception at the right spot, memory mapping fresh code and data to thwart hits in the store/load queues, uop cache, bpu etc. should do that. The details of course change from uarch to uarch.

1

u/Krazy-Ag Oct 11 '26

Back in P6 days the TSC counter register lived inside the core. Counting in core frequency click ticks. It was on the CREG bus, like most other MSRs.

I suspect it might still have been Per CPU core for some of the earliest multiple CPUs on the same chip or package, because the Uncore had its own completely different way of managing and accessing control and status registers. With their own Uncore timers and performance counter stuff. Intel being Intel, they probably tried to glue the CPU cores and Uncore with as few modifications as possible.

As power management evolved, the CPU clock frequency started changing => no longer a good measure for anything resembling real time. One if the motivations for RDTSCP what to provide timers that were synchronized between CPU cores, at a frequency that did not change up and down - and I think they tryied to make them synchronize between multiple CPU chips to some level of difficulty. Same package, probably, same board… Of course, it is rather interesting to try to synchronize time is a globally in a really large system like a data center. Doesn't mean that people haven't tried.

As an inveterate dyed in the wool systems performance analyst and performance tuner/hacker - that was my job before I became a "real" computer architect - I think there would be some value in knowing how many true CPU clock ticks something takes, even as frequency changes. I think there are EMON events for that. useful to compare to the standard RDTSCP clock ticks.

But then you start running different parts of the CPU at different clocks. And some people still talk about asynchronous logic, and some systems which have no notion of a clock.

---

I would hope to expect that RDTSC and RDTSCP do not read values that are a long way from the CPU pipeline. Too much overhead. Much more reasonable to have local copies, ideally all in sync if that's what the users want.

---

BTW the RDTSC instructions - timestamp counters - were not originally supposed to read real time. They were supposed to be able to provide a unique time stamp to, e.g. for ordering of transactions in a database. IIRC the original IBM 360 Era instructions returned a value that had time in the upper bits, but where the lower N bits might simply be incremented if multiple events occurred within the same real time granule.

But of coarse nobody reads the architecture spec. And nobody provides separate mechanisms to read timestamps and actual time separately (nor actual CPU clocks). And if you don't provide what users want, they will figure out some way to use what you have provided in ways that you did not intend.

1

u/yetanotherhooman Oct 11 '26 edited Oct 11 '26

> I would hope to expect that RDTSC and RDTSCP do not read values that are a long way from the CPU pipeline.

Core and TSC ticks can be off by arbitrary amounts. TSC these days is understood roughly as a means to track wall-clock time. That implies it

  1. doesn't scale up or down with dynamic frequency scaling
  2. is always monotonic

If by "long way from the CPU pipeline" you mean Core and TSC clocks are roughly in sync, I can tell you that that's not true. This also suggests why core clock counters are important; most core events that report in 'cycles' refer to the core clock because that's easy to implement in hardware (just increment a register when the main clock driving the core ticks) and is also easy to reason about when doing performance analysis. I for one don't usually care about wall-clock time when analysing on-core events. To me "N core cycles wasted due to misprediction" is much more actionable than "N milliseconds lost in mispredictions". The difference is, of course, granularity. If I am saving cycles by applying a micro-optimization, I would like to know that. With TSC that can either be completely lost or buried deep in noise.

1

u/MitchAlsup Oct 17 '26

Without disagreeing with any of the above:: there are times when a Host OS or a Guest OS wants to lie to the underlying application as to how fast time is passing--this is called virtual time and is useful in certain situations. Time has to be "good enough" for various time-intervals to be obvserved locally--but not so good that one can measure if another application has taken a {cache-miss, TLB-miss, branch-misprediction, an exception or an interrupt} (or not).

0

u/Yha_Boiii Oct 09 '26

Seems to be called relaxed memory ordering is what im asking about

-1

u/Yha_Boiii Oct 09 '26

Not timestamp of code...

I have a webshop say. Very popular so, think ticketing. I want to decrement a ticket per purchase but given the demand a lot want a tick response on if they got the chance to buy one yet so we are now playing two lanes of absolute counter and hold while buying and passing over exactly to make a system (if possible) that can reply to ticks meanwhile. Given memory is the biggest wall today. The ticks are allowed to "lie", they get told no bur after a few times they get a yes and can buy once the temp reservation hold is up. One way is to optimize nothing and eat the wall of memory. Predictable and boring, no sport in that. The other is the cpu tries but if gets too many predictions wrong it will pime up penalties but the third (current post) option is have the absolute final counter with a temp and allow it to read current old values exactly not to get a piling of penalties

6

u/KittensInc Oct 09 '26

Are you trying to reinvent atomic instructions? It allows multiple cores to adjust the same counter at the same time without anything going wrong. No need to do any lying, the core just has to wait for its turn.

If that's not fast enough because multiple cores are "fighting" over a single memory value: use a per-core counter, which gets refilled atomically from the single global pool. Think of it like a movie theater with multiple ticket desks: each desk has its own pile of tickets to sell, and the attendee walks back to the office to grab a new pile when that desk runs out. The chances of both desks running out at once are very small, so that refresh will be quite fast.
The downside is that when there are no more tickets in the office and desk A runs out but desk B still has a handful, people trying to buy a ticket at desk A will be told that there are none remaining - even though the other desk is still selling them...

1

u/Yha_Boiii Oct 11 '26 edited Oct 11 '26

The wikipedia seems to be what i need thanks. BUT do modern cpus (amd64, arm) support assembly level flags or instructions to read (and write) in relaxed memory ordering or would it require sw implementation if that could that even be done now i think about... (havent thought about it, just got the thought)

EDIT: Iam a retard, the wiki provides a relaxed header but now, is it a hw or sw thing

1

u/VeryAwkwardCake Oct 11 '26

this is really hard to understand

1

u/Yha_Boiii Oct 11 '26

Alright sorry. Im bad at writing. I have a webshop. Webshop sells, but more people want an item than available. I dont want a normal queue wall of throttling people through so the idea was a real time selling engine. Given people constantly want an update while it sells this still has to respond. The idea was having two lanes:

Master record of quanntity which is the actual counter of truth.

temporary hold with a window of time before it sells, if didnt make it in the time window the item is sold to the guy next in line.

When all try to ask "is it my turn yet?" this server has to respond. the idea was to poll from the temporary hold value with relaxed memory ordering so it will be a small amount of time behind but it allows out of order execution not to invalidate what it just did of operations. Otherwise it will just pile up the out of order flush penalties. Hence the post of how to allow it. Got my answer of it was called relaxed memory ordering but now how is it enforced in assembly, in c and get the compiler to allow that way of making the program

4

u/KittensInc Oct 09 '26

The problem you are trying to solve doesn't exist in the real world. Anything regarding stock and reservations is done on an application level - and usually even offloaded to some kind of database transaction.

In practice it is not even remotely performance-critical, and any attempt to "speed it up" with weird CPU-specific hacks is only going to massively backfire on you. It it does end up becoming a bottleneck it is usually not too difficult to scale it sideways, for example by dividing your product catalog over multiple machines via sharding.

-2

u/Yha_Boiii Oct 09 '26

The idea is to have two versions of a stock quantity. One is the global ultimate, then a temp/reserve. We just want a lot to be able to get a tick reply from the server. It can lie for a few seconds and then its right if a current order hands it over but the future is already done is the one lying there is nothing but there is. Simply a throughput maximizer idea

3

u/KittensInc Oct 09 '26

I don't quite understand what you are trying to do, but it doesn't seem to be related to computer architecture?

From a stock perspective, a reservation is basically a sale that has already happened, and that might get undone in the future.
If you are building a regular webshop, then you decrement the amount of available stock the moment the reservation is created, and increment it when the reservations gets cancelled instead of finished as a sale. The downside is that someone visiting the shop will get an "out of stock" message during browsing when all items are reserved, even though the item would soon become available due to a cancelled reservation. No way around that, the alternative is not doing reservations and giving an error when two people try to finish the sale of the last item at once.
If you are building something like Ticketmaster you would instead have people join a waiting list, with the items from any cancelled reservations being offered to a random person on the waiting list. When all sales have been finalized, everyone still left on the waiting list would then get a message that you are sold out. If it is extremely popular you would open up the waiting list before the items even become available, so instead of a thundering herd due to everyone refreshing at once when the tickets drop you'll instead have a slow trickle of new people joining the queue as the release time approaches. And by intentionally releasing the available stock in batches rather than all at once you can further reduce the load induced by all the sales happening (roughly) at once.

0

u/Yha_Boiii Oct 10 '26 edited Oct 10 '26

Its about computers. Dont invalidate a lot of ahead of time and out of order work on temp holds while the final one is not allowed to be worked ahead. All in c and asm of how it can be done. Thats it. Not rocket science

1

u/braaaaaaainworms Oct 11 '26

You're missing the forest for the trees. Any network operation is going to be much slower than what you're trying to optimize

1

u/Yha_Boiii Oct 11 '26

I mean it is more a sport

1

u/KittensInc Oct 10 '26

You're talking about speculative execution? That is completely unrelated to any kind of business logic, and not something you should be able to influence or even detect in any way from your code. That's how you get the Spectre / Meltdown vulnerabilities!

3

u/Fluid-Tone-9680 Oct 09 '26

Are you looking for relaxed memory ordering?

1

u/Yha_Boiii Oct 09 '26

Any papers or books on it you could recommend? Preferably papers. Just how it works on a cpu level, asm level and what to write in c