TweetFollow Us on Twitter

Taking Advantage of The Intel Core Duo Processor-Based iMac

Volume Number: 22 (2006)
Issue Number: 7
Column Tag: Performance Optimization

Taking Advantage of The Intel Core Duo Processor-Based iMac

How to make your applications run faster

by Ganesh Rao and Ron Wayne Green

Introduction

This is the first of a three part series that will address the most effective techniques to optimize applications for the Intel(R) Core(TM) Duo processor-based Macs. Part one introduces the key aspects of the Core Duo processor, and exposes the architectural features for which tuning is most important. A data-driven performance methodology using the software development tools available on a Mac to highlight tuning and optimization opportunities for a variety of applications is then described at length. Intel Core Duo processors feature two execution cores and each of the cores is capable of vector processing of data, referred to as the Intel(R) Digital Media Boost, which extends the Single Instruction Multiple Data (SIMD) technology. The second part of this series outlines how to take advantage of SIMD by enabling vectorization in the Intel Compiler. The final part of this 3-part series provides readers with the next level of optimization by taking advantage of both execution cores in addition to SIMD. We will cover auto-parallelization, where simple loops can be rendered parallel. And finally we will cover OpenMP, which are powerful user-specified directives embedded in source code to auto-magically tell the compiler to thread the application. You will love how easily you can thread applications while at the same time maintaining fine grain control of threads.

In this article, advanced and innovative software optimizations techniques supported by industry-leading compilers are addressed. These optimization techniques are used in the field every day to get better performance. Key topics will be illustrated with C++ and Fortran code snippets.

Intel Core duo processor

There is a rumor going around that Apple Macs now use an Intel processor, and a very happy Intel processor at that! All humor aside, we know that the MacTech community is gaining a very sophisticated understanding of the details of the Intel Core Duo processor. We want to call out features in the processor that, based on our experience, are most likely to increase the performance of your application. Stated differently, in this section we call out processor features that can be leveraged to extract better application performance. The Intel Core Duo processor includes two execution cores in a single processor. Please see Figure 1. Each of the execution cores supports Single instruction Multiple Data (SIMD), which involves performing multiple computations with a single instruction in parallel. Please see Illustration 2 for a diagrammatic representation of SIMD.



Figure 1: Intel(R) Core(R) Duo processor architectue



Figure 2: SIMD performs the same operation on multiple data

Applications that are most likely to benefit from SIMD are those that can be characterized as 'loopy'. SIMD is quite commonly seen in programs that spend a significant amount of time processing integers and/or floating point numbers in a loop. An example of this is a matrix-multiply operation. Intel Streaming SIMD Extensions (SSE), and the AIM Alliance AltiVec* instructions are example implementations of SIMD. In a subsequent article, part 2 of this 3-part series, we will get an opportunity to share our best practices to taking advantage of the SIMD processing capability in your processor.

SIMD extracts the best performance of a single core. Taking this to the next level, it is obvious that one needs to keep both cores busy to get maximal performance from an application. The most optimal way of taking advantage of both execution cores is to thread your application. We will share some of our best known methods to thread applications in the third part of the series. We will wrap up our three part discussion by highlighting innovative compiler technologies.

Drawing the baseline

The start of any performance optimization activity should be the clear definition of the performance baseline. The unit of the baseline could be either transactions per second, or more simply, the run-time of the application. Our experience is that we are setting ourselves up for failure if we do not have a clear, reproducible understanding of the baseline. Having a reproducible baseline also means clearly defining your benchmark application with the correct workload that is representative of anticipated usage. It may be worthwhile at this stage to consider if you can peel out a part of the application you wish to examine and wrap a main() function around it. This technique allows you to observe the behavior of the section of the application of most interest. You can then use the 'time' utility to measure the time spent by the program. In most production applications, it is difficult to completely separate the kernel that we wish to observe and improve performance. In these cases, it may be easier to insert timers in your code as shown below:

Example:

/* Sample Timing */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
   clock_t start, finish;
   long loop;
   double  duration, loop_calc;
   start = clock();
   // CODE TO BE MEASURED HERE
   //
   finish = clock();
   duration = (double)(finish - start)/CLOCKS_PER_SEC;
   printf("\n%2.3f seconds\n", duration);
}

While it is perfectly fine to use this 'time' API for applications and sections of code that run for a sufficient duration, the resolution of the clock is not fine enough for measuring a small, fast-running section of code.

An alternative is to use the rdtsc instruction (Read Time Stamp Counter). The rdtsc instruction returns the elapsed CPU clocks since the last reboot. This allows significantly higher resolution than using the 'time' API. Intel compilers implement a convenient intrinsic1 that makes it easy to measure rdtsc.

#include <stdio.h>
int main(void)
{
uint64_t start;
uint64_t stop;
uint64_t elapsed;
  
  #if __INTEL_COMPILER  
  // Start the counter
start=_rdtsc();  
#else   
  
  //Code to be measured here
  
  ...
  
//
#if __INTEL_COMPILER  
//Stop the counter
stop=_rdtsc();
elapsed = stop - start;
#else
//Calculate the runtime
elapsed = stop - start;
  printf("Processor cycles = %i64\n", elapsed); 
}

As of this writing, in some cases, rdtsc may report a wrong Time-Stamp counter value2. Using the technique described above with rdtsc does not work well if your thread switches context between the two cores, since the timer is separate on each core.

The other preferred alternative is to use the OS supported mach_absolute_time API abstraction.

#include <CoreServices/CoreServices.h>
#include <mach/mach.h>
#include <mach/mach_time.h>
int main(void)
{
    uint64_t        start;
    uint64_t        stop;
    uint64_t        elapsed;
    // Start the clock.
    start = mach_absolute_time();
    //Code to be measured here
  
    ...
  
    //
    // Stop the clock.
    stop = mach_absolute_time();
    // Calculate the run time
    elapsed = stop - start;
    printf("Processor cycles = %i64\n", elapsed); 
}

In the measurements we did, while mach_absolute_time and rdtsc seemed to provide answers that were close, there were small deviations. We need to clarify that while it may be comforting to think that we are measuring at the accuracy of clock-ticks, the measurements come bundled with a lot of variances. Specifically, you cannot measure the latency of a single instruction or even a bundle of instructions using either rdtsc or mach_absolute_time. In many cases, it is to the benefit of the programmer to set up benchmarks that have a sufficient runtime between start and stop timer. A sufficient runtime may be at a minimum on the order of tens or hundreds of seconds.

Hotspots in the code

Once we have a baseline, a powerful alternative to hand peeling code and inserting timers is to run a profiler to identify the hotspots in your code. Shark3 is a powerful tool to help you achieve this. We are not going to go into too much detail about using Shark in this article, since it is covered extensively elsewhere. Additionally, Shark can do much more than what we are calling out here. At a high level, Shark allows you to get a time profile which is based on sampling your code at fixed time intervals. Depending on your application, you may see profiles that are relatively flat, meaning there are no particular areas in your code that are exercised more than others. Or you could see clear peaks, which would mean that your program exercises a smaller portion of your code more extensively. Shark can clump the time profile by threads allowing you to see the profile of your code for each of the individual threads.

As a quick guide, start Shark from the hard disk at "/Developer/Applications/Performance Tools/CHUD"4. Figure 3 shows the start of a Shark session.



Figure 3: Shark Info window

Don't hit the Shark "start" button yet. First, start the application you need to profile. Hit the "start" button in Shark. Once started, Shark will automatically stop after 30 seconds or you can choose to hit "stop". Note that it is a good idea to take Shark snapshots over slightly extended periods to get repeatable results. Also, make sure that you have stopped running other applications so as to not pollute the profile gathered. Depending on your application, you may choose to start after your application has "warmed up" or progressed beyond startup initializations and initial file IO. If you are experienced with your application and its runtime behavior, it is relatively easy to know the hotspots in your code, and where they occur during a typical run. Thus, a correct technique is to monitor your application's log output, determine when the hotspot is started, start Shark, and gather a profile over a sufficient length of time.



Figure 4: Shark Time Profile

Note that at this stage it may still be to your advantage to insert timers in your code with print-statements as we saw in the previous section around the areas of code that are of interest to you.

Using the techniques highlighted above, we can gain insight into the operating characteristics of programs, and understand where we can make a difference. We can generally think of performance improvement for the serial portion of the code, but also consider threading the code and consider performance improvements due to threading. We can do a back-of-the-envelope estimate of the potential degree to which the performance of the overall application can be optimized due to serial improvements in the code, using Amdahl's law, as illustrated below.

Let us say that the hotspot or the section of the serial code we are optimizing is taking up fraction x of the total program run time. Then a speedup of fraction y on this section of the code should theoretically improve overall performance by 1/ ((1-x) + x/y). As a limiting condition, the theoretical maximum speedup possible is 1/(1-x). The limiting maximum speed up would occur if the section of the code we are considering takes zero time to run. As an example, if a section we are focused on is taking 50% of the total run time (x = .5), and we provide a doubling of speed (y = 2) in this section, we can expect an overall speedup of 1/(.5+(.5/2)) = 1/.75 = 1.33 or 33% speedup of the overall performance. As a theoretical maximum, we can get a 2x performance gain for the whole application where fraction x = .5, when speedup y tends to infinity.

Once we determine where we can make a difference, and how much of a difference we can make, we can then look at ways and means in which to make improvements. Please note that while in this article we are looking at serial improvements, in a future article we will look at estimating and planning for parallel improvements in detail.

One other related note before we end this section. Note that compilers as part of optimization can completely eliminate chunks of code it determines will not effect the outcome of the final program, also referred to as dead code elimination. While this is a very good thing for real applications, you need to be careful to ensure that the compilers do not throw away the performance kernel you have extracted in a snippet program in order to examine. Typically an output statement of the result will be all that is required to ensure that the Compiler does not eliminate the small section of code.

COMPILERS

This may sound like a cliche, but perhaps the first and the foremost tool at your disposal to make a performance difference should be your compiler. In addition to the GNU (gcc) Compiler, we will be discussing using the Intel(R) C++ compiler in the following sections. Both compilers integrate into Apple's Xcode Integrated Development Environment, and are binary and source compatible. Fortran developers can use the Intel(R) Fortran Compiler for Mac OS or several GNU options including g77, gfortran, or G95. While GNU is invoked with the 'gcc' command line, Intel Compilers are invoked with the 'icc' command line for C/C++ and the 'ifort' command for Fortran. While the examples that follow use the Intel C/C++ compiler, the same options apply to the Intel Fortran compiler (ifort).

Generally speaking, newer versions of the compiler optimize for systems running newer processors. You can verify the version of the compiler by using the -v flag.

$ icc -v
Version 9.1
$ gcc -v
Using built-in specs.
Target: i686-apple-darwin8
Configured with: /private/var/tmp/gcc/gcc-5250.obj~12/src/configure --disable-checking 
-enable-werror --prefix=/usr --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ 
--program-transform-name=/^[cg][^.-]*$/s/$/-4.0/ --with-gxx-include-dir=/include/c++/4.0.0 
--build=powerpc-apple-darwin8 --with-arch=pentium-m --with-tune=prescott --program-prefix= 
--host=i686-apple-darwin8 --target=i686-apple-darwin8
Thread model: posix
gcc version 4.0.1 (Apple Computer, Inc. build 5250)
  

Here is a very brief run down of the general optimization options available with the compilers. O0 (gcc -O0 or icc -O0) means no optimization is turned on. While it may be helpful to have O0 option to debug applications, your application will run at significant sub-optimal speed at this option level.

O1 and O2 are higher levels of optimization. O1 usually makes optimization tradeoffs that result in smaller compile time compared to O2.

O3 is the highest level of optimization and makes aggressive decisions on optimizations that require a judgment call between the size of the generated code, and the expected resulting speed of the application.

We should note here that despite throwing the best optimization options, compilers can still use your help. As an example, let us look at an often overlooked performance hit: denormals5, denormalized IEEE floating point representations in your code, can trigger exceptions that could result in severe runtime penalties. This is because denormals may require hardware and the OS to intervene in operations using denormal operands. When your application frequently uses very small numbers, you should consider taking advantage of the flush-to-zero (also referred to as FTZ for short) feature. The FTZ feature allows the CPU to take denormal values in registers within the CPU, and convert those values to zero, a valid IEEE representation. FTZ is default when using SIMD.

Consider the following example where denormals are deliberately triggered for illustration. Here, we look at the timing between gcc and icc for the following example:

#include <stdio.h>
main()
{
        long int i;
        double coefficient = .9;
        double data = 3e-308;
        for (i=0; i < 99999999; i++)
        {
                data *= coefficient;
        }
        printf("%f\t %x\n", data, *(unsigned long*)&data);
}
$ g++ -O3 denormal.cpp -o gden
$ time ./gden
0.000000         5
   real    0m13.462s
user    0m12.676s
sys     0m0.041s
$ icc denormal.cpp -o iden
denormal.cpp(8) : (col. 9) remark: LOOP WAS VECTORIZED.
$ time ./iden
0.000000         0
real    0m0.178s
user    0m0.138s
sys     0m0.006s

Notice that since the loop was fairly simple, the Intel compiler was able to vectorize the loop, and therefore use SIMD. Because Flush-To-Zero is the default when using SIMD registers, notice that the runtime improvement can be dramatic. We will dive into SIMD and auto-vectorization in more detail in the next installment of this series of articles.

Next installment

Now that we had a chance to go through the introductions, in the next installment, we will see how to pack a punch in your optimizations, without going through the tedious process of hand assembling instructions or even intrinsics. We will accomplish this by taking advantage of the Auto-vectorization feature. And yes, if you have Altivec code or SSE instructions that you are intending to migrate to take advantage of Auto-vectorization, then the next installment is a must read for you!

In the meantime, hopefully you will get the chance to visit with some members of the Intel Software Development Products team at WWDC.


Both authors are members of the Intel Compiler team. Ganesh Rao has been with Intel for over nine years and currently helps optimize applications to take advantage of the latest Intel processors using the Intel Compilers.

Ron Wayne Green has been involved in Fortran and high-performance computing applications development and support for over twenty years, and currently assists with Fortran and high-performance computing issues.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.