Elapsed Time Mac OS

Using the Intel® Power Gadget API on Mac OS X*

Timer is a simple chronometer application. Enter a value and click 'Start' to count down any number of hours, minutes, and seconds, or start at zero to track elapsed time. Sep 29, 2018 Occasionally in Mac OS X, it may be necessary to force a program or process to quit. For example, if a particular program fails to respond or unexpectedly hangs. Every application on a Mac comprises of one or more processes. It’s usually possible to use the Force Quit command (⌘⌥ esc) in the Apple Menu, but.

  • The professional timer app. Timer is a complete and professional stopwatch, alarm clock, timer and clock utility for Mac. It has an easy-to-use and very intuitive interface with clear tab-based browsing thru stopwatch, timer, alarm clock and clock areas. Timer is free to download and you can freely use it.
  • This is all elapsed time including time slices used by other processes and time the process spends blocked (for example if it is waiting for I/O to complete). User is the amount of CPU time spent in user-mode code (outside the kernel) within the process. This is only actual CPU time used in executing the process.
  • To use the Elapsed Time Calculator, input the start and end dates and times in the format '1/1/2008 12:01:00 AM'. The time can be left off, but a date must be present. Midnight is assumed if no date is specified. Press the 'Calculate Elapsed Time' button to calculate the amount of time that has passed between the two dates and times.

Intel® Power Gadget for Mac* is a GUI application that provides real-time data on processor frequency and estimated processor power, and can log frequency, power, energy, and temperature data over time. Intel® Power Gadget also provides a C Application Programming Interface (API) for accessing this power and frequency data in your program. Intel® Power Gadget is also available for Windows* and Linux*. Intel® Power Gadget and the API are only supported on 2nd generation and later Intel® Core processors, because previous processors do not support the necessary power Model Specific Registers (MSRs).

Intro to the Intel® Power Gadget API

The Intel® Power Gadget API is a framework (IntelPowerGadget .framework) that provides a C interface for reading current estimated processor power, current processor frequency, base frequency, thermal design power (TDP), current temperature, maximum temperature, timestamps, and elapsed time. It also provides logging functionality.

What You Need

To use the API you’ll need the Intel® Power Gadget for Mac* driver and framework. These are included in the Intel® Power Gadget installer, or as a standalone API installer. The driver is installed to /System/Library/Extensions/EnergyDriver.kext, and the framework is installed to /Library/Frameworks/IntelPowerGadget.framework.

To link with the Intel® Power Gadget API you simply need to include
–framework IntelPowerGadget in your link command.

Using the Intel® Power Gadget API

To begin you must initialize the library by calling IntelEnergyLibInitialize.

The most common use of the Intel® Power Gadget API is to read samples with ReadSample. The API supports sampling of specific Model Specific Registers (MSRs). Meta data on the sampled MSRs can be queried with GetNumMsrs, GetMsrName, and GetMsrFunc. GetNumMsrs returns the number of sampled MSRs; MSRs are given an ID from 0 to n-1, where n is the number returned by GetNumMsrs. The MSR ID is used to get data for a specific MSR with functions GetPowerData, GetMsrName, and GetMsrFunc.

Calling GetPowerData for each sampled MSR will provide you with the relevant data from that MSR. An MSR’s function (from GetMsrFunc) determines the amount and meaning of data returned from GetPowerData. MSRs with function 0 (frequency) return 1 result, which represents the frequency in megahertz. MSRs with function 1 (power) return 3 results, which represent the average power in watts, cumulative energy in Joules, and cumulative energy in milliwatt-hours. MSRs with function 2 (temperature) return 1 result, which represents the temperature in degrees Celsius. The Intel® Power Gadget API currently supports sampling with the following MSRs: processor frequency, estimated processor power, and package temperature. The currently supported MSR functions are: frequency (0), power (1), temperature (2).

ReadSample also reads the system time and Time Stamp Counter (TSC) at the time the sample is read. These values are available via GetSysTime and GetRDTSC; the time interval between samples is available (in seconds) via GetTimeInterval. Note that you must call ReadSample prior to calling GetPowerData, GetRDTSC, and GetTimeInterval, and that you must call ReadSample twice before calling GetTimeInterval and before getting power data (as opposed to frequency or temperature data) from GetPowerData, as they are computed using the difference between two samples.

The Intel® Power Gadget API also supports reading generic MSRs with ReadMSR, which returns the raw data from the MSR. However, note that specifying an invalid MSR address can crash your system and could potentially corrupt it. There is no method to determine if an MSR address is valid. The API supports reading common individual MSRs without having to specify the MSR address or read an entire sample; the supported functions are: GetIAFrequency, GetMaxTemperature, GetTemperature, and GetTDP.

The sample data from ReadSample can be logged to a file. Logging can be enabled at any time by calling StartLog, and subsequently disabled by calling StopLog. Note that the logged data isn’t written until StopLog is called. Both StartLog and StopLog cause an internal call to ReadSample.

Sampling Considerations

The frequency at which you read samples may have an impact on the accuracy of data. The instantaneous processor frequency can change significantly from moment to moment. Frequency data may be more meaningful if you sample often and average the frequency samples over time. The processor power is calculated by taking the difference between two samples, thus a shorter interval between samples will result in more fine-grained power data. However, the frequency at which you read samples may also impact the performance of the system. Using a very short frequency (e.g. less than 20 milliseconds) may result in significant overhead, and may also increase the power consumption of the system, both of which may reduce the usefulness of the data. The Intel® Power Gadget application uses a default sampling frequency of 50 milliseconds, and updates the GUI with averaged frequency and power data every second.

Example

Download the Xcode project for this example application here.

API Reference

Initializes the library and connects to the driver.

Returns the number of CPU packages on the system.

Returns the number of supported MSRs for bulk reading and logging.

Returns in szName the name of the MSR specified by iMsr. Note that the Windows version uses wchar_t.

Returns in pFuncID the function of the MSR specified by iMsrCurrently supported functions are: 0 = frequency, 1 = power, 2 = temperature.

Reads the MSR specified by address on the package specified by iNode, and returns the value in value. Warning: Specifying an invalid MSR address can crash your system and could potentially corrupt it. There is no method to determine if an MSR address is valid.

Reads the processor frequency MSR on the package specified by iNode, and returns the frequency in MHz in freqInMHz.

Reads the package power info MSR on the package specified by iNode, and returns the TDP in watts in TDP.

Reads the temperature target MSR on the package specified by iNode, and returns the maximum temperature in degrees Celsius in degreeC.

Reads the temperature MSR on the package specified by iNode, and returns the current temperature in degrees Celsius in degreeC.

Reads sample data from the driver for all the supported MSRs. Note that two calls to ReadSample are necessary to calculate power data, as power data is calculated using the difference between two samples.

Returns the system time as of the last call to ReadSample. The data returned in pSysTime is structured as follows:

pSysTime[63:32] = time in seconds

pSysTime[31:0] = time in nanoseconds

Returns in pTSC the processors time stamp counter as of the last call to ReadSample. Note that this function does not execute the rdtsc instruction directly, but instead returns the TSC from when the last sample was read.

Returns in pOffset the time in seconds that has elapsed between the two most recent calls to ReadSample.

Returns in pBaseFrequency the advertised processor frequency for the package specified by iNode.

Returns the data collected by the most recent call to ReadSample. The returned data is for the data on the package specified by iNode, from the MSR specified by iMSR. The data is returned in pResult, and the number of double results returned in pResult is returned in nResult. Frequency MSRs (function 0) return 1 result, which represents the frequency in megahertz. Power MSRs (function 1) return 3 results, which represent the average power in watts, cumulative energy in Joules, and cumulative energy in milliwatt-hours. Temperature MSRs (function 2) return 1 result, which represents the temperature in degrees Celsius.

Starts saving the data collected by ReadSample. When StopLog is called, this data will be written to the file specified by szFileName. Note that the Windows version uses wchar_t. StartLog will cause an initial call to ReadSample.

Stops saving data and writes all saved data to the file specified by the call to StartLog. StopLog will cause a final call to ReadSample.

[Update: this post has been updated with significant new information. Look to the end.]

Activity Monitor is a tool in Mac OS X that shows a variety of real-time process measurements. It is well-known and its “Energy Impact” measure (which was added in Mac OS X 10.9) is often consulted by users to compare the power consumption of different programs. Apple support documentation specifically recommends it for troubleshooting battery life problems, as do countless articles on the web.

However, despite its prominence, the exact meaning of the “Energy Impact” measure is unclear. In this blog post I use a combination of code inspection, measurements, and educated guesses to hypothesize how it is computed in Mac OS X 10.9 and 10.10.

What is known about “Energy Impact”?

The following screenshot shows the Activity Monitor’s “Energy” tab.

There are no units given for “Energy Impact” or “Avg Energy Impact”.

Mac Os Mojave

The Activity Monitor documentation says the following.

Energy Impact: A relative measure of the current energy consumption of the app. Lower numbers are better.

Avg Energy Impact: The average energy impact for the past 8 hours or since the Mac started up, whichever is shorter.

That is vague. Other Apple documentation says the following.

The Energy tab of Activity Monitor displays the Energy Impact of each open app based on a number of factors including CPU usage, network traffic, disk activity and more. The higher the number, the more impact an app has on battery power.

More detail, but still vague. Enough so that various other people have wondered what it means. The most precise description I have found says the following.

If my recollection of the developer presentation slide on App Nap is correct, they are an abstract unit Apple created to represent several factors related to energy usage meant to compare programs relatively.

I don’t believe you can directly relate them to one simple unit, because they are from an arbitrary formula of multiple factors.

[…] To get the units they look at CPU usage, interrupts, and wakeups… track those using counters and apply that to the energy column as a relative measure of an app.

This sounds plausible, and we will soon see that it appears to be close to the truth.

A detour: top

First, a necessary detour. top is a program that is similar to Activity Monitor, but it runs from the command-line. Like Activity Monitor, top performs periodic measurements of many different things, including several that are relevant to power consumption: CPU usage, wakeups, and a “power” measure. To see all these together, invoke it as follows.

(A non-default invocation is necessary because the wakeups and power columns aren’t shown by default unless you have an extremely wide screen.)

It will show real-time data, updated once per second, like the following.

The PID, COMMAND and %CPU columns are self-explanatory.

The IDLEW column is the number of package idle exit wakeups. These occur when the processor package (containing the cores, GPU, caches, etc.) transitions from a low-power idle state to the active state. This happens when the OS schedules a process to run due to some kind of event. Common causes of wakeups include scheduled timers going off and blocked I/O system calls receiving data.

What about the POWER column? top is open source, so its meaning can be determined conclusively by reading the powerscore_insert_cell function in the source code. (The POWER measure was added to top in OS X 10.9.0 and the code has remain unchanged all the way through to OS X 10.10.2, which is the most recent version for which the code is available.)

The following is a summary of what the code does, and it’s easier to understand if the %CPU and POWER computations are shown side-by-side.

The %CPU computation is as expected.

The POWER computation is a function of CPU and IDLEW. It’s basically the same as %CPU but with a “tax” of 500 microseconds for each wakeup and an exception for kernel processes. The value of this function can easily exceed 100 — e.g. a program with zero CPU usage and 3,000 wakeups per second will have a POWER score of 150 — so it is not a percentage. In fact, POWER is a unitless measure because it is a semi-arbitrary combination of two measures with incompatible units.

Elapsed Time Mac Os 7

Back to Activity Monitor and “Energy Impact”

MacBook Pro running Mac OS X 10.9.5

First, I did some measurements with a MacBook Pro with an i7-4960HQ processor running Mac OS X 10.9.5.

I did extensive testing with a range of programs: ones that trigger 100% CPU usage; ones that trigger controllable numbers of idle wakeups; ones that stress the memory system heavily; ones that perform frequent disk operations; and ones that perform frequent network operations.

In every case, Activity Monitor’s “Energy Impact” was the same as top‘s POWER measure. Every indication is that the two are computed identically on this machine.

For example, consider the data in the following table, The data was gathered with a small test program that fires a timer N times per second; other than extreme cases (see below) each timer firing causes an idle platform wakeup.

Mac os versions

The table shows a variety of measurements for this program for different values of N. Columns 2–5 are from powermetrics, and show CPU usage, interrupt frequency, and package idle wakeup frequency, respectively. Column 6 is Activity Monitor’s “Energy Impact”, and column 7 is top‘s POWER measurement. Column 6 and 7 (which are approximate measurements) are identical, modulo small variations due to the noisiness of these measurements.

MacBook Air running Mac OS X 10.10.4

I also tested a MacBook Air with an i5-4250U processor running Mac OS X 10.10.4. The results were substantially different.

The results from top are very similar to those from the other machine. But Activity Monitor’s “Energy Impact” no longer matches top‘s POWER measure. As a result it is much harder to say with confidence what “Energy Impact” represents on this machine. I tried tweaking the previous formula so that the idle wakeup “tax” drops from 500 microseconds to 180 or 200 microseconds and that gives results that appear to be in the ballpark but don’t match exactly. I’m a bit skeptical whether Activity Monitor is doing all its measurements at the same time or not. But it’s also quite possible that other inputs have been added to the function that computes “Energy Impact”.

What about “Avg Energy Impact”?

What about the “Avg Energy Impact”? It seems reasonable to assume it is computed in the same way as “Energy Impact”, but averaged over a longer period. In fact, we already know that period from the Apple documentation that says it is the “average energy impact for the past 8 hours or since the Mac started up, whichever is shorter.”

Indeed, when the Energy tab of Activity Monitor is first opened, the “Avg Energy Impact” column is empty and the title bar says “Activity Monitor (Processing…)”. After a few seconds the “Avg Energy Impact” column is populated with values and the title bar changes to “Activity Monitor (Applications in last 8 hours)”. If you have top open during those 5–10 seconds can you see that systemstats is running and using a lot of CPU, and so presumably the measurements are obtained from it.

systemstats is a program that runs all the time and periodically measures, among other things, CPU usage and idle wakeups for each running process (visible in the “Processes” section of its output.) I’ve done further tests that indicate that the “Avg Energy Impact” is almost certainly computed using the same formula as “Energy Impact”. The difference is that the the measurements are from the past 8 hours of wake time — i.e. if a laptop is closed for several hours and then reopened, those hours are not included in the calculation — as opposed to the 1, 2 or 5 seconds of wake time used for “Energy Impact”.

battery status menu

Even more prominent than Activity Monitor is OS X’s battery status menu. When you click on the battery icon in the OS X menu bar you get a drop-down menu which includes a list of “Apps Using Significant Energy”.

How is this determined? When you open this menu for the first time in a while it says “Collecting Power Usage Information” for a few seconds, and if you have top open during that time you see that, once again, systemstats is running and using a lot of CPU. Furthermore, if you click on an application name in the menu Activity Monitor will be opened and that application’s entry will be highlighted. Based on these facts it seems reasonable to assume that “Energy Impact” is again being used to determine which applications show up in the battery status menu.

I did some more tests (on my MacBook Pro running 10.9.5) and it appears that once an energy-intensive application is started it takes about 20 or 30 seconds for it to show up in the battery status menu. And once the application stops using high amounts of energy I’ve seen it take between 4 and 10 minutes to disappear. The exception is if the application is closed, in which case it disappears immediately.

Finally, I tried to determine the significance threshold. It appears that a program with an “Energy Impact” of roughly 20 or more will eventually show up as significant, and programs that have much higher “Energy Impact” values tend to show up more quickly.

All of these battery status menu observations are difficult to make reliably and so should be treated with caution. They may also be different in OS X 10.10. It is clear, however, that the window used by the battery status menu is measured in seconds or minutes, which is much less than the 8 hour window used for “Avg Energy Impact”.

An aside: systemstats is always running on OS X. The particular invocation used for the long-running instance — the one used by both Activity Monitor and the battery status menu — takes the undocumented --xpc flag. When I tried running it with that flag I got an error message saying “This mode should only be invoked by launchd”. So it’s hard to know how often it’s making measurements. The output from vanilla command-line invocations indicate it’s about every 10 minutes.

But it’s worth noting that systemstats has a -J option which causes the CPU usage and wakeups for child processes to be attributed to their parents. It seems likely that the --xpc option triggers the same behaviour because the Activity Monitor does not show “Avg Energy Impact” for child processes (as can be seen in the screenshot above for the login, bash and vim processes that are children of the Terminal process). This hypothesis also matches up with the battery status menu, which never shows child processes. One consequence of this is that if you ssh into a Mac and run a power-intensive program from the command line it will not show up in Activity Monitor’s energy tab or the battery status menu, because it’s not attributable to a top-level process such as Terminal! Such processes will show up in top and in Activity Monitor’s CPU tab, however.

How good a measure is “Energy Impact”?

Elapsed Time Mac Os Mdickie

We’ve now seen that “Energy Impact” is used widely throughout OS X. How good a measure is it?

The best way to measure power consumption is to actually measure power consumption. One way to do this is to use an ammeter, but this is difficult. Another way is to measure how long it takes for the battery to drain, which is easier but slow and requires steady workloads. Alternatively, recent Intel hardware provides high-quality estimates of processor and memory power consumption that are relatively easy to obtain.

These approaches all have the virtue of measuring or estimating actual power consumption (i.e. Watts). But the big problem is that they are machine-wide measures that cannot be used on a per-process basis. This is why Activity Monitor uses several proxy measures — ones that correlate with power consumption — which can be measured on a per-process basis. “Energy Impact” is a hybrid of at least two different proxy measures: CPU usage and wakeup frequency.

The main problem with this is that “Energy Impact” is an exaggerated measure. Look at the first table above, with data from the 10.9.5 machine. The variation in the “Pkg Power” column — which shows the package power from the above-mentioned Intel hardware estimates — is vastly smaller than the variation in the “Energy Impact” measurements. For example, going from 1,000 to 10,000 wakeups per second increases the package power by 3.4x, but the “Energy Impact” increases by 9.7x, and the skew gets even worse at higher wakeup frequencies. “Energy Impact” clearly weights wakeups too heavily. (In the second table, with data from the 10.10.4 machine, the weight given to wakeups is less, but still too high.)

Also, in the first table “Energy Impact” actually decreases when the timer frequency gets high enough. Presumably this is because the timer interval is so short that the OS has trouble putting the package into a idle power state. This leads to the absurd result that firing a timer at 1,000 Hz has about the same “Energy Impact” value as firing one at 100,000 Hz, when the package power of the latter is about 7.5x higher.

Having said all that, it’s understandable why Apple uses formulations of this kind for “Energy Impact”.

  • CPU usage and wakeup frequency are probably the two most important factors affecting a process’s power consumption, and they are factors that can be measured on a per-process basis.
  • Having a single measure makes things easy for users; evaluating the relative important of multiple measures is more difficult.
  • The exception for kernel processes (which always have an “Energy Impact” of 0) avoids OS X itself being blamed for high power consumption. This makes a certain amount of sense — it’s not like users can close the kernel — while also being somewhat misleading.

If I were in charge of Apple’s Activity Monitor product, I’d do two things.

  1. I would compute a new formula for “Energy Impact”. I would measure the CPU usage, wakeup frequency (and any other inputs) and actual power consumption for a range of real-world programs, on a range of different Apple machines. From this data, hopefully a reasonably accurate model could be constructed. It wouldn’t be perfect, and it wouldn’t need to be perfect, but it should be possible to come up with something that reflects actual power consumption better than the existing formulations. Once formulated, I would then test the new version against synthetic microbenchmarks, like the ones I used above, to see how it holds up. Given the choice between accurately modelling real-world applications and accurately modelling synthetic microbenchmarks, I would definitely favour the former.
  2. I would publicly document the formula that is used so that developers can actually tell how their applications are being evaluated, and can optimize for that measure. You may think “but then developers will be optimizing for a synthetic measure rather than a real one” and you’d be right. That’s an inevitable consequence of giving a synthetic measure such prominence, and all the more reason for improving it.

Conclusion

“Energy Impact” is a flawed measure of an application’s power consumption. Nonetheless, it’s what many people use at this moment to evaluate the power consumption of OS X applications, so it’s worth understanding. And if you are an OS X application developer who wants to reduce the “Energy Impact” of your application, it’s clear that it’s best to focus first on reducing wakeup frequency, and then on reducing CPU usage.

Because Activity Monitor is closed source code I don’t know if I’ve characterized “Energy Impact” exactly correctly. The evidence given above indicates that I am close on 10.9.5, but not as close on 10.10.4. I’d love to hear if anybody has evidence that either corroborates or contradicts the conclusions I’ve made here. Thank you.

Update

A commenter named comex has done some great detective work and found on 10.10 and 10.11 Activity Monitor consults a Mac model-specific file in the /usr/share/pmenergy/ directory. (Thank you, comex.)

For example, my MacBook Air has a model number 7DF21CB3ED6977E5 and the file Mac-7DF21CB3ED6977E5.plist has the following list of key/value pairs under the heading “energy_constants”.

This matches the previously seen formula, but with the wakeups “tax” being 200 microseconds, which matches what I hypothesized above.

“QoS” refers to quality of service classes which allow an application to mark some of its own work as lower priority. I’m not sure exactly how this is factored in, but from the numbers above it appears that operations done in the lowest-priority “background” class is considered to have an energy impact of about half that done in all the other classes.

These ones are straightforward. Note that the “tax” for disk reads is zero, and for disk writes it’s a very small number. I wrote a small program that wrote endlessly to disk and saw that the “Energy Impact” was slightly higher than the CPU percentage alone, which matches expectations.

It makes sense that GPU usage is included in the formula. It’s not clear if this refers to the integrated GPU or the separate (higher performance, higher power) GPU. It’s also interesting that the weighting is 3x.

Mac

These are also straightforward. In this case, the number of bytes sent is ignored, and only the number of packets matter, and the cost of reading and writing packets is considered equal.

Elapsed Time Mac Os Catalina

So, in conclusion, on 10.10 and 10.11, the formula used to compute “Energy Impact” is machine model-specific, and includes the following factors: CPU usage, wakeup frequency, quality of service class usage, and disk, GPU, and network activity.

Elapsed Time Mac Os X

This is definitely an improvement over the formula used in 10.9, which is great to see. The parameters are also visible, if you know where to look! It would be wonderful if all these inputs, along with their relative weightings, could be seen at once in Activity Monitor. That way developers would have a much better sense of exactly how their application’s “Energy Impact” is determined.