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.

 
AAPL
$101.32
Apple Inc.
+0.74
MSFT
$45.15
Microsoft Corpora
-0.07
GOOG
$582.56
Google Inc.
-0.81

MacTech Search:
Community Search:

Software Updates via MacUpdate

Garmin Express 3.2.17.0 - Manage your Ga...
Garmin Express is your essential tool for managing your Garmin devices. Update maps, golf courses and device software. You can even register your device. Update maps Update software Register your... Read more
Audio Hijack Pro 2.11.1 - Record and enh...
Audio Hijack Pro drastically changes the way you use audio on your computer, giving you the freedom to listen to audio when you want and how you want. Record and enhance any audio with Audio Hijack... Read more
calibre 2.0.0 - Complete e-library manag...
Calibre is a complete e-book library manager. Organize your collection, convert your books to multiple formats, and sync with all of your devices. Let Calibre be your multi-tasking digital... Read more
Apple iMovie 10.0.5 - Edit personal vide...
With an all-new design, Apple iMovie lets you enjoy your videos like never before. Browse your clips more easily, instantly share your favorite moments, and create beautiful HD movies and Hollywood-... Read more
Apple Keynote 6.2.2 - Apple's prese...
Apple Keynote makes it simple to create and deliver beautiful presentations. Powerful tools and dazzling effects bring your ideas to life. You can work seamlessly between Mac and iOS devices. And... Read more
Apple Numbers 3.2.2 - Apple's sprea...
With Apple Numbers, sophisticated spreadsheets are just the start. The whole sheet is your canvas. Just add dramatic interactive charts, tables, and images that paint a revealing picture of your data... Read more
OpenOffice 4.1.1 - Free and open-source...
OpenOffice.org is both an Open Source product and a project. The product is a multi-platform office productivity suite. It includes the key desktop applications, such as a word processor,... Read more
Pages 5.2.2 - Apple's word processo...
Apple Pages is a powerful word processor that gives you everything you need to create documents that look beautiful. And read beautifully. It lets you work seamlessly between Mac and iOS devices. And... Read more
Quicken 2015 2.0.1 - Complete personal f...
The new Quicken 2015 helps you manage all your personal finances in one place, so you can see where you're spending and where you can save. Quicken automatically categorizes your financial... Read more
CleanMyMac 2.2.7 - Delete files that was...
CleanMyMac makes space for the things you love. Sporting a range of ingenious new features, CleanMyMac 2 lets you safely and intelligently scan and clean your entire system, delete large, unused... Read more

Latest Forum Discussions

See All

Trolls vs Vikings Update Adds Over One H...
Trolls vs Vikings Update Adds Over One Hundred Levels, Reduces Item Cost, and More Posted by Ellis Spice on August 22nd, 2014 [ permalink ] | Read more »
SNK Celebrates the 20th Anniversary of T...
SNK Celebrates the 20th Anniversary of The King of Fighters With a Big Sale Posted by Ellis Spice on August 22nd, 2014 [ permalink ] | Read more »
It Came From Canada: Star Wars: Commande...
With a brand new Star Wars trilogy on the horizon, prepare yourselves for Disney and George Lucas’s space fantasy throwback to be more omnipresent than ever before. So it should come as no surprise that new adventures in that galaxy far, far away... | Read more »
Swing Copters Review
Swing Copters Review By Jordan Minor on August 22nd, 2014 Our Rating: :: DIE TRYINGUniversal App - Designed for iPhone and iPad The creator of Flappy Bird is back with a vengeance.   | Read more »
Beam Me an Update Scotty – Star Trek Tre...
Beam Me an Update Scotty – Star Trek Trexels Receives its Biggest Update Yet Posted by Jessica Fisher on August 22nd, 2014 [ permalink ] | Read more »
The Outcast Review
The Outcast Review By Nadia Oxford on August 22nd, 2014 Our Rating: :: HANDS OFF. WAY OFF.Universal App - Designed for iPhone and iPad It’s easy to see what The Outcast is trying for, but its execution needs a lot of work.   | Read more »
HeroCraft Unveils New iOS Game, Marble D...
HeroCraft Unveils New iOS Game, Marble Duel Posted by Jessica Fisher on August 22nd, 2014 [ permalink ] HeroCraft is developing a new chain popper game called Marble Duel, wh | Read more »
Brain+ Review
Brain+ Review By Nadia Oxford on August 22nd, 2014 Our Rating: :: DIM BULBUniversal App - Designed for iPhone and iPad Brain+ is just another entry in an over-saturated brain-training marketplace – and not a particularly fun entry... | Read more »
The Witcher Battle Arena – New Gameplay...
The Witcher Battle Arena – New Gameplay Trailer Revealed Posted by Jessica Fisher on August 22nd, 2014 [ permalink ] Based in the Witcher universe, | Read more »
Max Gentlemen Review
Max Gentlemen Review By Jennifer Allen on August 22nd, 2014 Our Rating: :: OUTSTAYING ITS WELCOMEiPhone App - Designed for the iPhone, compatible with the iPad Max Gentlemen seems pretty quirky initially but that appeal wears thin... | Read more »

Price Scanner via MacPrices.net

Updated Mac Price Trackers
We’ve updated our Mac Price Trackers with the latest information on prices, bundles, and availability on systems from Apple’s authorized internet/catalog resellers: - 15″ MacBook Pros - 13″ MacBook... Read more
Leftover 15-inch 2.0GHz Retina MacBook Pros a...
B&H Photo has leftover previous-generation 15″ 2.0GHz Retina MacBook Pros now available for $1599 including free shipping plus NY sales tax only. Their price is $400 off original MSRP. B&H... Read more
Pro.Calendar – New Productivity App for iPad...
Austin, Texas based mobile business and productivity app developer LightArrow, Inc. has announced Pro.Calendar, a powerful and intuitive calendar app with eight versatile calendar options including... Read more
SanDisk Ultra II SSD — Supercharge Your Syste...
SanDisk Corporation has announced the new SanDisk Ultra II SSD with enhanced SSD Dashboard. The new drive is designed to deliver a cost-effective and easy upgrade solution for PC owners looking to... Read more
Samsung and Barnes & Noble Introduce New...
Samsung Electronics America and NOOK Media, a subsidiary of Barnes & Noble, Inc. have announced the introduction of the new Samsung Galaxy Tab 4 NOOK, a 7-inch tablet combining Samsung’s leading... Read more
21-inch iMacs on sale for up to $150 off MSRP
B&H Photo has 21″ iMacs on sale for up to $150 off MSRP including free shipping plus NY sales tax only. B&H will also include a free copy of Parallels Desktop software: - 21″ 2.7GHz iMac: $... Read more
27-inch 3.2GHz iMac on sale for $1698, save $...
Abt has the 27″ 3.2GHz iMac on sale for $1698 including free shipping. Their price is $101 off MSRP. Read more
Mac Backup Guru 2.0 Drive Backup/Cloneing Uti...
Mac Backup Guru developer MacDaddy has released Mac Backup Guru 2.0, offering new and enhanced advanced features, such as bootable backups, synchronised volumes and folders, and a Snapshot mode that... Read more
Operate GE’s New Free-Standing KItchen Range...
Think you accidentally left the oven on? Switch it off while on the go. The new free-standing Profile™ Series gas and electric ranges are GE’s second cooking appliances, following their wall oven, to... Read more
Parallels Announces Parallels Desktop 10 for...
The no. 1-selling software for running Windows applications on a Mac becomes an even easier choice for millions of consumers and IT professionals worldwide with the launch of the most powerful... Read more

Jobs Board

Position Opening at *Apple* - Apple (United...
…customers purchase our products, you're the one who helps them get more out of their new Apple technology. Your day in the Apple Store is filled with a range of Read more
Position Opening at *Apple* - Apple (United...
**Job Summary** As businesses discover the power of Apple computers and mobile devices, it's your job - as a Solutions Engineer - to show them how to introduce these Read more
Position Opening at *Apple* - Apple (United...
**Job Summary** At the Apple Store, you connect business professionals and entrepreneurs with the tools they need in order to put Apple solutions to work in their Read more
Project Manager / Business Analyst, WW *Appl...
…a senior project manager / business analyst to work within our Worldwide Apple Fulfillment Operations and the Business Process Re-engineering team. This role will work Read more
*Apple* Retail - Multiple Positions (US) - A...
Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, you're also the Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.