Quantcast
Channel: Intermediate
Viewing all 664 articles
Browse latest View live

intel.xdk.cache

$
0
0

For persistent caching of data between application sessions.

This object is intended to provide local storage for data to speed up applications. It can be used as in conjunction with, or as an alternative to the HTML5 local database. Its methods provide features similar to browser cookies and file caching.

For cookies, the intention is that you would use setCookie to save string data in name-value pairs. Cookies persist between application sessions. Data values may be retrieved using the getCookie command or from the getCookieList command as soon as the "intel.xdk.device.ready" event is fired. The media cache commands are meant to provide quicker access to files such as videos and images. Adding files to the media cache will expedite access to them when the application runs. These are files that are cached across sessions and are not in your application bundle. See the section on events below for more information about events fired from the cache section of intel.xdk.
Object
Type
Notes
intel.xdk.cache.addToMediaCachemethodThis command will get a file from the Internet and cache it locally on the device.
intel.xdk.cache.addToMediaCacheExtmethodThis command will get a file from the Internet and cache it locally on the device. More details
intel.xdk.cache.clearAllCookiesmethodThis method will clear all data stored using the setCookie method. More details
intel.xdk.cache.clearMediaCachemethodThis command will remove all files from the local cache on the device.
intel.xdk.cache.getCookiemethodThis method will retrieve the value of a cookie previously saved using the setCookie command.
intel.xdk.cache.getCookieListmethodThis method will return an array containing the names of all the previously saved cookies using the setCookie command.
intel.xdk.cache.getMediaCacheListmethodThis method will get an array containing all the names of all the previously cached files.
intel.xdk.cache.getMediaCacheLocalURLmethodThis method will return an url that you can use to access a cached media file.
intel.xdk.cache.getMediaCacheRelativePathmethodundocumented
intel.xdk.cache.removeCookiemethodThis method will clear data previously saved using the setCookie method.
intel.xdk.cache.removeFromMediaCachemethodThis command will remove a file from the local cache on the device.
intel.xdk.cache.setCookiemethodCall this method to set a chunk of data that will persist from session to session.
intel.xdk.cache.media.addeventFires when data is cached
intel.xdk.cache.media.cleareventFired once all files are removed from the local file cache
intel.xdk.cache.media.removeeventFired when data is removed from the cache
intel.xdk.cache.media.updateeventFired repeatedly to track caching progress

Supplemental Documentation

addToMediaCacheExt - This object is intended to provide local storage for data to speed up applications. It can be used as in conjunction with, or as an alternative to the HTML5 local database. Its methods provide features similar to browser cookies and file caching.

intel.xdk.cache.addToMediaCacheExt(urlToCache,uniqueID);function cacheUpdated(evt)
{var outString = "";
        outString += "current bytes downloaded: " + evt.current;
        outString += " total bytes in download: " + evt.total;var percentage = evt.current/evt.total
}

clearAllCookies - This method will clear all data stored using the setCookie method.

intel.xdk.cache.clearAllCookies(urlToCache,uniqueID);function cacheUpdated(evt)
{var outString = "";
        outString += "current bytes downloaded: " + evt.current;
        outString += " total bytes in download: " + evt.total;var percentage = evt.current/evt.total
}

Состояния управления электропитанием: P-состояния, C-состояния и пакетные C-состояния

$
0
0

(Вы можете скачать PDF-версию этой статьи во вложении.)

Содержание

Предисловие. Что, почему и откуда? 1

Глава 1: Введение. 2

Глава 2: P-состояния, Снижение энергопотребления без ущерба для производительности. 3

Глава 3: С-состояния ядер. Подробности. 5

Глава 4: Пакетные C-состояния. Подробности. 8

Глава 5: Интуитивное описание состояний электропитания с помощью человечков и лампочек. 12

Заключение. 15

Приложение: C-Состояния, P-Состояния, а где же T-Состояния?. 16

Справочные материалы. 18

Примечания. 18

 

Предисловие. Что, почему и откуда?

В этой статье объединена серия публикаций, посвященных состояниям управления электропитанием. Эта серия входит в еще более крупный набор блогов по самым разным темам, связанным с управлением электропитанием, включая состояния управления электропитанием (эта серия), состояния электропитания в режимах «Турбо» и в режиме hyper-threading, настройку и политики управления электропитанием. Содержание этих публикаций будет полезно для всех, хотя здесь описывается только сопроцессор Intel® Xeon Phi™. Исключение составляет лишь серия по настройке, которая по своей природе в большей степени зависит от платформы; она посвящена сопроцессору Intel® Xeon Phi™ и набору программ Intel® Manycore Platform Software Stack (MPSS). В дополнение к этому набору блогов по управлению электропитанием обратите внимание на еще две вспомогательных подборки: серию по измерению производительности[i], и еще один набор более ранних публикаций на различные темы, например о том, откуда берется C*V2*f.

Статья, которую вы сейчас читаете, была изначально опубликована в следующей серии из весьма непоследовательно названных блогов:

Кроме того, есть еще одна статья в приложении:

На портале Intel® Developer Zone вы найдете отдельные блоги, перечисленные в еще одной статье: Список полезных статей, блогов и ссылок по электропитанию и управлению электропитанием.

Итак, устраивайтесь поудобнее и постарайтесь получить удовольствие от ознакомления с захватывающей темой управления электропитанием.

 

Глава 1. Введение для пытливых умов

Какие именно состояния электропитания существуют для сопроцессора Intel Xeon Phi? Что происходит в каждом из этих состояний? Было бы интересно знать. Если вы интересуетесь высокопроизводительными вычислениями, то и вам эти знания пригодятся.

Но это не будет глубокий, исчерпывающее подробный и крайне технический научный труд, посвященный управлению электропитанием. Если вам нужен именно такой материал, предлагаю прочесть руководство разработчиков программного обеспечения (SDG) по сопроцессору Intel Xeon Phi[ii].Но предупреждаю: когда в разделе руководства разработчиков, посвященном управлению электропитанием, заходит речь о создателях программного обеспечения (т. е. о программистах), явно или неявно, подразумеваемся не мы с вами. Целевая аудитория этого руководства — разработчики операционных систем и драйверов. Кстати, в прошлой жизни я был одним из таких разработчиков. Одна из целей этой серии блогов — рассмотрение управления электропитанием с точки зрения разработчика приложений, т. е. меня или вас, а не с точки зрения создателя операционных систем или драйверов.

Кроме того, я не стану рассказывать о том, что такое С-, Р- и РС-состояния. Если вам требуется ознакомиться с этими понятиями перед чтением нашей серии блоков, рекомендую (без ложной скромности) мою прежнюю серию блогов, посвященную именно этой теме. См. http://software.intel.com/en-us/user/266847/track. Непросто выделить нужные публикации по управлению электропитанием из всех прочих моих публикаций в форумах и видеороликов, поэтому я перечислил наиболее важные публикации в примечании[iii].

Если кратко, бывают Р-состояния пакета, С-состояния ядер (иногда их называют СС-состояния) и С-состояния пакета (РС-состояния). Также сопроцессор может работать в режиме "Turbo"3. Р-состояний ядер не бывает.

Хост и сопроцессор совместно отвечают за управление электропитанием сопроцессора. В некоторых операциях по управлению электропитанием сопроцессор действует автономно. В других случаях хост принимает ответственность на себя и сам управляет электропитанием, а иногда даже переопределяет действия сопроцессора.

В дальнейшей серии я расскажу о пакетных Р-состояниях (включая режим "Turbo"[iv]), C-состояниях ядер и пакетных РС-состояниях. Я также расскажу о том, как вы, будучи разработчиком приложений, можете управлять электропитанием сопроцессора..

И еще одно замечание. Я не гарантирую, что все выпуски сопроцессоров Intel Xeon Phi (т. е. типы сопроцессоров) поддерживают все эти функции управления электропитанием.

 

Глава 2. P-состояния. Снижение энергопотребления без ущерба для производительности

С самого начала могу заявить, что Р-состояния не повлияют на производительность приложения. Тем не менее они важны для приложения по другим соображениям. Поскольку большинство читателей этого блога ничего не принимают на веру, относятся ко всей воспринимаемой информации критически и скептически (будучи инженерами и учеными), я подкреплю это мое заявление доказательствами.

Р-состояния представляют собой пары значений напряжения и частоты, определяющие скорость работы сопроцессора и потребляемую им мощность. Чем ниже рабочее напряжение процессора, тем меньше электроэнергии он потребляет. (В одной из более ранних публикаций я пояснял это на очень высоком техническом уровне.) Поскольку вместе с напряжением снижается и частота, при этом уменьшается скорость вычислений. Так и вижу, как у вас зреет вопрос: «Да разве могут возникнуть ситуации в приложениях для высокопроизводительных вычислений, когда мне потребуется включить Р-состояния и снизить производительность приложения?» Применение Р-состояний менее важно в области высокопроизводительных вычислений, чем в средах с менее интенсивной нагрузкой, таких как клиентские компьютеры и серверы данных. Но даже в среде сопроцессоров и высокопроизводительных вычислений длительные состояния бездействия довольно часто возникают в промежутках между крупными вычислительными задачами. Например, если вы используете модель разгрузки, сопроцессор с высокой вероятностью не будет использоваться в периодах между разгрузками. Кроме того, нативное приложение, выполняющееся на сопроцессоре, зачастую будет по разным причинам находиться в состоянии бездействия, например ожидать следующей порции данных для обработки.

Программа управления электропитанием сопроцессора поддерживает Р-состояния от Р0 до Pn. Количество Р-состояний, поддерживаемых каждым выпуском (типом) сопроцессора, может различаться, но всегда составляет не менее двух. Кроме того, некоторые типы поддерживают Р-состояния «Турбо». Программа управления электропитанием сопроцессора обрабатывает переходы из одного Р-состояния в другое. Программа управления электропитанием хоста в этом практически не участвует.

Возникает закономерный вопрос: как это все повлияет на производительность? Мы же все-таки работаем в среде высокопроизводительных вычислений. Ответ прост: никакого практического влияния на производительность вычислений нет. Не сомневаюсь, что сейчас у вас возникло уже несколько вопросов:

(a)    “Минутку! Как это возможно? Если сопроцессор снижает скорость работы процессора, уменьшая его частоту, как это может не повлиять на производительность моего приложения?”

(b)   “Мне просто нужно, чтобы приложение работало как можно быстрее. Зачем вообще мне заботиться о сокращении потребления электроэнергии?”

Сначала рассмотрим вариант Б. Я понимаю, что электропитание не является наиболее приоритетным вопросом для вас, как для разработчика приложений. Но все равно оно косвенно влияет на производительность приложения. Повышенное потребление электроэнергии связано с такими вещами, как более высокие затраты на помещение, повышенный расход электричества на охлаждение и кондиционирование воздуха, необходимость большей площади помещения и т. п. Просто об этом должны заботиться не мы (программисты), а наши коллеги — администраторы, системные архитекторы, управляющие помещениями и так далее.

Говоря по правде, вам тоже следует думать об этом. Это влияет на ваше приложение с весьма важной стороны, хоть это и не всегда очевидно. Если в вычислительном центре удастся снизить расход электроэнергии без потери производительности, это означает, что в этом же пространстве можно установить больше процессоров, не превышая при этом отведенную норму электропитания. То есть, образно говоря, вы «получаете больше за те же деньги». А это очень хорошо для вас как для программиста или ученого. Снижение требуемой потребляемой мощности означает, что в меньшем пространстве можно разместить больше процессоров. Это, в свою очередь, означает, что вы как разработчик приложений или ученый можете заниматься не только более масштабными задачами (в системе больше ядер), но и обрабатывать эти задачи быстрее (ниже задержки передачи данных между ядрами).

Вернемся к Р-состояниям. Р-состояния теоретически повлияют на производительность, но не так, чтобы это сказалось на работе высокопроизводительных приложений. Как это возможно? Дело в переходах между Р-состояниями. Также следует помнить об использовании процессора. Программное обеспечение управления электропитанием периодически отслеживает использование процессора. Если использование ниже определенного порога, Р-состояние увеличивается, то есть процессор переходит в следующее состояние энергоэффективности. Ключевое слово в предыдущем предложении — «использование». Как вы думаете, каково будет использование процессора при выполнении ресурсоемкой задачи, связанной с высокопроизводительными вычислениями? В идеале оно должно быть как можно ближе к 100 %. А в каком Р-состоянии будет выполняться ваше приложение при таком использовании процессора? Это Р0, самое быстрое Р-состояние (если не считать режим «Турбо»). Следовательно, Р-состояния с самым высоким уровнем экономии электричества не повлияют на ваше приложения: ситуация, в которой процессор, поддерживающий ваше хорошо настроенное высокопроизводительное приложение, мог бы войти в одной из таких состояний, просто не возникнет.

Итак, все высокопроизводительные части приложения всегда будут использовать процессоры почти на 100 %. Использование, близкое к 100 %, практически всегда гарантирует самое быстрое Р-состояние, то есть Р0. Следовательно, Р-состояния не влияют на производительность приложений.

Как заставить мое приложение работать в одном из этих режимов «Турбо»? Этого делать нельзя, потому что это слишком опасно. Очень легко сделать незначительную ошибку, которая повлечет перегрев и повреждение сопроцессора. Если процессор поддерживает «Турбо», предоставьте управление этим режимом операционной системе.

 

Глава 3. C-состояния ядер: подробности

БАЗОВЫЕ СВЕДЕНИЯ: КРАТКО О СОСТОЯНИЯХ БЕЗДЕЙСТВИЯ

Вот краткое описание С-состояний. С-состояния — это состояния экономии электроэнергии при бездействии (в отличие от Р-состояний, представляющих собой состояния экономии электроэнергии при работе). В Р-состоянии процессор продолжает выполнять инструкции, а в С-состоянии (кроме состояния С0) процессор бездействует, никакие инструкции не выполняются. Можно привести такую аналогию: бездействующий процессор подобен дому, в котором горит весь свет, но никого нет. Потребление всей этой электроэнергии не служит никаким полезным целям, разве что приносит некоторую прибыль электрической компании. Как лучше поступить? Если дома никого нет, то есть дом бездействует, зачем же оставлять свет включенным? То же самое применимо и к процессору. Если им никто не пользуется, зачем подавать питание на неиспользуемые элементы и расходовать электричество? Можно отключить их и сэкономить.

С0 является «нулевым» состоянием электропитания: в этом состоянии ядро фактически работает, не бездействует.

РАЗНИЦА МЕЖДУ СОСТОЯНИЯМИ БЕЗДЕЙСТВИЯ ЯДЕР И ПАКЕТА

Сопроцессор содержит до 60 (или даже больше) ядер в одном пакете. Состояния бездействия ядер (C-состояния) действуют для каждого ядра: одно из этих 60 ядер может быть в состоянии C0, т. е. ядро работает и не бездействует, тогда как соседнее ядро может находиться в состоянии глубокой экономии электроэнергии C6. PC-состояния — это состояния бездействия всего пакета, то есть состояния экономии электроэнергии для всех 60 ядер и поддерживающих электронных компонентов на кристалле. Как можно догадаться, чтобы перевести пакет в состояние PC-6, все ядра должны находиться в состоянии С6. Почему? Поскольку пакет обладает функциональностью, поддерживающей все ядра, «отключение» определенных электронных компонентов пакета влияет на все ядра.

Рисунок 1. Перевод ядра в состояние С1

 

КАКИЕ СУЩЕСТВУЮТ СОСТОЯНИЯ БЕЗДЕЙСТВИЯ ЯДЕР?

У каждого ядра может быть два состояния бездействия, С1 и С6 (не считая С0).

Переход от С0 к С1. Посмотрите на рис. 1 Состояние С1 наступает, когда все 4 аппаратных потока, поддерживаемых ядром, выполняют инструкцию HALT. Давайте посмотрим на каждый аппаратный поток с точки зрения операционной системы: 4 аппаратных потока рассматриваются как 4 отдельных ЦП (от ЦП 0 до ЦП 3). Этап 1. Первые три ЦП, принадлежащие данному ядру, выполняют инструкцию HALT. Этап 2. Последний ЦП (ЦП 0) пытается выполнить инструкцию HALT. Этап 3. Он прерывается для процедуры сбора данных резидентности бездействия. Эта процедура, как вы догадались, собирает данные резидентности бездействия и сохраняет их в структуре данных, доступной для ОС. Затем ЦП 0 выполняет инструкцию HALT. Этап 4. На этом этапе все ЦП останавливаются, а ядро переходит в состояние C1. В состоянии ядра C1 (и его ЦП) снижается его тактовая частота[v].

 

Рисунок 2. Следует ли переходить в С6: достаточно ли далеко следующее прерывание?

 

Рисунок 3. Следует ли переходить в С6: достаточно ли велико предполагаемое время бездействия?

После входа ядра в состояние C1 на сцену выходит программа управления электропитанием сопроцессора. Ей нужно определить, целесообразно ли дальнейшее отключение ядра и перевод его в состояние С6. В состоянии ядра C6 остальные части ядра отключаются, их потребляемая мощность ограничивается. Помните, что программа управления электропитанием сопроцессора выполняется на ядре ОС (обычно это ядро 0), поэтому отключения других ядер на него не влияют.

Решения какого типа должна принимать программа управления электропитанием сопроцессора? Существует два основных решения, описанных в предыдущей главе. Вопрос 1. Будет ли (возможно) достигнута экономия электроэнергии? Вопрос 2. Сможет ли задержка, требуемая для перезапуска, отрицательно повлиять на производительность процессора или применений, выполняемых на этом процессоре? Эти решения соответствуют двум основным сценариям и показаны на рисунках 2 и 3. В сценарии 1 программа управления электропитанием сопроцессора определяет, насколько далеко следующее запланированное или предполагаемое прерывание. Если прерывание должно произойти достаточно скоро, не имеет смысла отключать ядро, поскольку увеличивается длительность задержки, необходимой для возврата ядра в состояние С0. Как и в жизни, процессор ничего не получает бесплатно. За переход в более глубокое С-состояние процессор расплачивается повышением задержек, связанных с возвратом ядра/пакета в рабочее состояние. В сценарии 2 программа управления электропитанием сопроцессора изучает историю деятельности ядра (то есть его аппаратных потоков) и определяет по чередованию периодов работы (состояние С0) и бездействия (С1), даст ли какую-либо экономию переход в состояние С6.

При ответе «да» на оба этих вопроса ядро переходит в состояние С6.

После входа в состояние ядра C6 процессор принимает решение о том, может ли он перейти в одно из состояний бездействия пакета. Этому вопросу будет посвящена следующая публикация в моем блоге.

 

Глава 4. C-состояния пакета: подробности

ЗАМЕЧАНИЕ О ТЕРМИНОЛОГИИ.

Если вы прочтете SDG (руководство разработчика программного обеспечения по сопроцессорам Intel Xeon Phi), то вы обнаружите там множество не всегда понятных названий и сокращений. Вот как это все расшифровывается:

Пакетный Auto C3[vi] - также называется Auto-C3, AutoC3, PC3, C3, Auto-PC3 и Package C3.

Пакетный Deep-C3 - также называется PC3, DeepC3, DeeperC3, Deep PC3 и Package C3 (я не повторяюсь, это вам показалось).

Пакетный C6 - также называется PC6, C6 и Package C6.

БАЗОВЫЕ СВЕДЕНИЯ: ЧТО ТАКОЕ «ВНЕЯДЕРНЫЕ КОМПОНЕНТЫ»?

Перед более подробным рассмотрением С-состояний пакета сначала несколько слов о компонентах современных процессоров Intel®. Всю электронную «начинку» процессора очень удобно разделить на две части: то, что образует ядра (конвейер, вычислительные блоки, регистры, кеш и т. д.) и все остальное (вспомогательные элементы). Оказывается, что это «все остальное» можно снова разделить на вспомогательные элементы, не связанные напрямую с производительностью (например, интерфейс с PCI Express), и на элементы, связанные с производительностью (например, шины, соединяющие ядра). В Intel для вот этих вспомогательных элементов, напрямую влияющих на производительность оптимизированных приложений, придумали обозначение «внеядерные компоненты».

 

 

Рисунок 4. Типы электронных компонентов сопроцессора

 

Вернемся к нашим С-состояниям.

ЗАЧЕМ НУЖНЫ C-СОСТОЯНИЯ ПАКЕТА?

Помимо ограничения тактов каждого ядра, какие еще методики можно использовать для дополнительной экономии электроэнергии? Вот простейший и даже банальный пример того, что можно сделать: отключить питание всего процессора. При этом потребление электроэнергии будет равно нулю, хотя и недостатки такого «выдергивания из розетки» также очевидны. Лучше избирательно отключать более глобальные компоненты процессора таким образом, чтобы можно было относительно быстро вернуть процессор в полностью функциональное состояние (С0).

Именно для этого и используются пакетные С-состояния: для последовательного отключения дополнительных компонентов с целью дальнейшей экономии электроэнергии. Поскольку мы уже отключили все компоненты пакета, связанные с ядрами, оставшиеся компоненты являются общими и необходимыми для всех ядер, поэтому их совокупность мы и называем пакетом.

КАКИЕ СУЩЕСТВУЮТ СОСТОЯНИЯ БЕЗДЕЙСТВИЯ ПАКЕТА?

Уважаемые читатели, существуют три пакетных С-состояния: Auto-C3, Deep-C3 и (пакетный) C6. Напоминаю, что это все пакетные С-состояния, то есть все аппаратные потоки/ЦП во всех ядрах находятся в состоянии HALT. Я догадываюсь, о чем вы думаете: «Если все ядра сопроцессора находятся в состоянии HALT, как может работать программное обеспечение управления электропитанием?» Хороший вопрос. Но ответ, если подумать, вполне очевиден. Если программное обеспечение управления электропитанием не может выполняться на сопроцессоре, то где может? Разумеется, на хосте.

 

Рисунок 5. Области ответственности сопроцессора и хоста при управлении электропитанием

 

За управление электропитанием сопроцессора Intel® Xeon Phi™ отвечают два компонента: программа управления электропитанием, выполняющаяся на сопроцессоре и компонент управления электропитанием драйвера сопроцессора MPSS, выполняющийся на хосте. См. рис. 1. Сопроцессор управляет переходом в различные С-состояния ядра и выходом из них. Разумеется, когда программа управления электропитанием не может выполняться на сопроцессоре, например при состояниях пакета Deep-C3 или C6, управление берет на себя хост. Управление пакетным состоянием Auto-C3 осуществляет и хост, и сопроцессор.

ЧТО ОТКЛЮЧАЕТСЯ В С-СОСТОЯНИЯХ ПАКЕТА?

Я собирался переделать эту таблицу, но в ней все настолько ясно, что я ее просто скопировал. Это таблица 3-2 из руководства разработчиков программного обеспечения (SDG) по сопроцессору Intel® Xeon Phi™.

Состояние бездействия пакета

Состояние ядра

Состояние внеядерных компонентов

TSC/LAPIC

C3WakeupTimer

Трафик PCI Express*

PC3

Сохраняется

Сохраняется

Приостановка

После окончания срока действия пакет выходит из состояния РС3

Пакет выходит из состояния РС3

Deep C3

Сохраняется

Сохраняется

Приостановка

Не влияет

Истекает время ожидания

PC6

Утрачивается

Утрачивается

Сброс

Не влияет

Истекает время ожидания

 

Немного подробнее:

Пакетный Auto-C3: ограничение частоты кольца и внеядерных компонентов

Пакетный Deep-C3: снижение напряжения VccP

Пакетный C6: отключение напряжения VccP (т. е. отключение питания ядер, кольца и внеядерных компонентов)

TSC и LAPIC — это тактовые генераторы, которые останавливаются при отключении внеядерных компонентов. Их следует правильным образом задать при повторной активации пакета. PC3 — это то же самое, что состояние пакета Auto-C3.

КАК ОПРЕДЕЛЯЮТСЯ ПЕРЕХОДЫ С-СОСТОЯНИЙ БЕЗДЕЙСТВИЯ ПАКЕТА?

В Auto-C3 пакета: первое состояние пакета, Auto-C3, можно рассматривать как промежуточное. Программа управления электропитанием сопроцессора может инициировать переход в это состояние. Программа управления электропитанием MPSS может переопределить этот запрос при определенных условиях, например если хост «знает», что внеядерная часть сопроцессора по-прежнему работает.

Мы также увидим, что состояние пакета Auto-C3 — единственное, которое может быть инициировано программой управления электропитанием сопроцессора. Поначалу это кажется немного несправедливым, но, если вдуматься, причина очевидна. В начале перехода в состояние пакета Auto-C3 процедура управления электропитанием сопроцессора запущена и может инициировать переход в первое состояние пакета. (Чтобы быть совсем точным, ядро, на котором выполняется программа управления электропитанием, может быстро перейти в состояние С0.)

Ниже состояния Auto-C3 сопроцессор не выполняет код. Переход в более глубокие С-состояния контролируется программой управления электропитанием хоста. Причина не только в том, что к этому моменту собственная программа управления электропитанием сопроцессора уже приостановлена, но и в том, что хост располагает более глобальной информацией о происходящем, например данными о работе внеядерных компонентов после ограничения работы всех ядер, и о трафике в шине PCI Express.

В пакетном Deep-C3 программа управления электропитанием хоста анализирует историю резидентности бездействия, прерывания (например, трафик PCI* Express) и временные затраты на пробуждение сопроцессора из состояния пакета Deep-C3, чтобы принять решение о том, следует ли переводить процессор из состояния пакета Auto-C3 в состояние пакета Deep-C3.

В пакетномC6 так же, как и в пакетном Deep-C3, но глубже.

 

Глава 5. Интуитивное описание состояний электропитания с помощью человечков и лампочек

ИНТУИТИВНАЯ ИЛЛЮСТРАЦИЯ ЯДРА И ЕГО АППАРАТНЫХ ПОТОКОВ

Это четвертая публикация в серии записей об управлении электропитанием для сопроцессоров Xeon Phi.

Для тех из вас, кто прочел мой блог с интуитивным введением в сопроцессор Intel Xeon Phi, Сопроцессор Intel Xeon Phi: что это такое и какое мне до этого дело? Часть 3. Если отвлечься от избитой аналогии с зайцам и черепахами,я как-то упомянул «опытных программистов, старательно работающих на своих корпоративных работодателей». Давайте немного расширим эту концепцию. На рис. 6 у нас есть один опытный программист. Он символизирует один аппаратный поток сопроцессора ЦП.

http://software.intel.com/sites/default/files/powerBlog_states_pt3_FigA_high_tech_worker_3.png

Рисунок 6. Опытный программист, то есть аппаратный поток Intel® Xeon Phi™

 

В ядре — 4 аппаратных потока. Посмотрите на рисунок 7. Все настолько очевидно, что я не стану утруждать себя написанием, а вас — чтением многостраничного пояснения. Также изображена и лампочка. Лампочка представляет инфраструктуру, поддерживающую ядро, такую как тактовые контуры и цепи питания.

http://software.intel.com/sites/default/files/powerBlog_states_pt3_FigB_high_tech_workers_0.png

Рисунок 7. Опытные программисты в комнате, т. е. ядро сопроцессора Intel® Xeon Phi™

 

УПРАВЛЕНИЕ ЭЛЕКТРОПИТАНИЕМ: ЯДРА C0 И C1

Какое отношение все это имеет к управлению электропитанием? Иногда отдельные либеральные студенты гуманитарных направлений заявляют, что инженеры лишены воображения и вообще зануды. Но мы-то с вами знаем, что даже если некоторое занудство нам порой не чуждо, то в отсутствии изображения нас обвинить нельзя. Помня об этом, представьте себе, что на каждом из этих столов стоят компьютеры и настольные лампы.

Ядро в режиме C0: кода хотя бы один опытный программист напряженно работает (т. е. хотя бы один аппаратный поток ядра ЦП выполняет инструкции)

ЦП выполняет инструкцию HALT: когда один из наших опытных программистов заканчивает работу, он выключает свою настольную лампу, выключает компьютер и уходит (т. е. один из аппаратных потоков выполняет инструкцию HALT).

После входа в состояние ядра C1: когда все четыре опытных программиста заканчивают работу, они все выполняют инструкции HALT. Последний из них гасит за собой свет в помещении. (Т. е. снижение тактовой частоты ядра.)

 

УПРАВЛЕНИЕ ЭЛЕКТРОПИТАНИЕМ: СОСТОЯНИЕ ЯДРА C6

После входа в состояние ядра C6: да, я понимаю, что это очевидно, но мне нравится разговаривать с самим собой. С течением времени все уходят на обед. Поскольку в офисе никого нет, можно отключить еще больше электроприборов (т. е. снижение потребляемой мощности). Впрочем, помните, что работники вернутся после обеда, поэтому нужно иметь возможность быстро включить все выключенное.

 

http://software.intel.com/sites/default/files/powerBlog_states_pt3_FigC_building_of_high_tech_workers_1.png

Рисунок 8. Здание, полное опытных программистов, т. е. сопроцессор Intel® Xeon Phi™

 

УПРАВЛЕНИЕ ЭЛЕКТРОПИТАНИЕМ: СОСТОЯНИЯ ПАКЕТА AUTO-C3, DEEP-C3 И C6

Да, эта аналогия могла вам уже поднадоесть, но мне она нравится, так что продолжаем.

Давайте пройдем немного дальше. Представьте здание, в котором очень много комнат, больше 60. Посмотрите на рисунок 8. Да, я знаю, что у нас в Кремниевой долине опытные программисты работают в великолепных и просторных комнатах, а не в тесных общих офисах. К сожалению, на этом моя аналогия останавливается, потому что мне нужен именно обычный офис.

Вход в состояние пакета Auto-C3: все ушли с этажа, поэтому датчик движения автоматически выключает освещение на этаже. (Т. е. программное обеспечение управления сопроцессором снижает рабочую частоту внеядерных компонентов и прочих вспомогательных элементов кристалла.

Вход в состояние пакета Deep-C3: сейчас выходные, поэтому во всем здании (т. е. в модуле управления электропитанием драйвера сопроцессора MPSS) отключено кондиционирование воздуха и выключена телефонная связь. (Т. е. хост снижает напряжение VccP сопроцессора и заставляет его игнорировать прерывания)

Вход в состояние пакета C6: новогодние каникулы: офис закрыт, все сотрудники добровольно или вынужденно отдыхают, поэтому техническая служба офиса отключила электричество, кондиционирование воздуха, телефоны, серверы, лифты, туалеты и пр. (т. е. хост выключил питание сопроцессора и отключил отслеживание трафика PCI Express*).

УПРАВЛЕНИЕ ЭЛЕКТРОПИТАНИЕМ: ЧЕМ ДАЛЬШЕ, ТЕМ ЧУДЕСНЕЕ

Увлекшись этой нашей аналогией, я решил было расширить ее до комплексов офисных зданий (узел, содержащий несколько сопроцессоров), международных инженерных дивизионов (кластеры, в которых каждый узел содержит несколько сопроцессоров) и до привлечения внешних партнеров (распределенная обработка в глобальной сети). Впрочем, здравый смысл победил, поэтому я отказался от этого замысла.

 

 

Заключение

Мы обсудили различные типы состояний управления электропитанием. Это достаточно широкая проблема, но мы сосредоточились на определенной платформе — сопроцессоре Intel® Xeon Phi™. Большинство современных процессоров, будь то процессоры корпорации Intel, корпорации AMD* или встроенные решения, обладают такими состояниями в той или иной разновидности.

Процессоры Intel® поддерживают два типа состояний управления электропитанием: P-состояния (работа) и C-состояния (бездействие). С-состояния, в свою очередь, делятся еще на две категории: состояния ядер и состояния пакета. Р-состояния — это состояния работы (С0) процессора; снижение потребляемой мощности в этих состояниях достигается путем снижения напряжения и частоты процессора. С-состояния — это состояния бездействия; они отключают части процессора, когда ядра простаивают. Существует два типа С-состояний. C-состояния ядер отключают части отдельных ядер/ЦП. Поскольку современные процессоры содержат несколько ядер, С-состояния пакетов отключают электронные элементы, поддерживающие все эти ядра.

Чистый эффект этих состояний заключается в значительном снижении энергопотребления современных процессоров Intel®. Такая экономия электроэнергии может быть весьма значительной, в некоторых случаях потребление электроэнергии снижается на порядок.

Важность экономии потребляемой мощности невозможно переоценить для любых систем, от смартфонов до высокопроизводительных кластеров. Например, снижение потребляемой мощности и энергопотребления отдельных процессоров в кластере для высокопроизводительных вычислений дает возможность установить в этой системе больше процессоров. При этом повышается плотность процессоров, ускоряется обмен информацией между узлами, становится возможным создать гораздо более мощную систему, способную решать более крупные и сложные задачи. На противоположном краю — портативные устройства с пассивным охлаждением, такие как смартфоны и планшеты. В них снижение потребляемой мощности позволяет дольше работать от аккумулятора без подзарядки и исключает проблемы, связанные с охлаждением. Это позволяет устанавливать в такие устройства более мощные процессоры, что, в свою очередь, расширяет возможности этих устройств.

 

Приложение. C-состояния, P-состояния, а где же T-состояния?

Несколько дней назад мне встретился интересный вопрос: «Важно ли понимать Т-состояния?» Сначала я удивился: «Что еще за Т-состояния?»

Впрочем, изучив материал, я обнаружил, что так называемое Т-состояние действительно существует, но уже не используется, по крайней мере в серийных процессорах Intel® его нет.

Поэтому повторяю: Т-состояния нам безразличны!

На этом более практичные читатели могут перейти к более актуальным темам, а я расскажу немного из истории управления электропитанием.

Когда-то раньше существовали Т-состояния — это были состояния регулировки. Задолго до появления С- и Р-состояний Т-состояния были придуманы, чтобы защитить процессоры от повреждений при авариях, например если при работе процессора на полной мощности отказывал охлаждающий вентилятор. Если простейший правильно расположенный термодатчик определял, что температура достигала уровня, на котором возможны повреждения пакета или его содержимого, аппаратный диспетчер питания переводил процессор в различные Т-состояния в зависимости от температуры: чем выше температура, тем выше Т-состояние.

AКак вы, возможно, догадались, обычный режим работы процессора назывался состоянием Т0. При переходе процессора в более высокое Т-состояние диспетчер ограничивал такты ядер, чтобы замедлить выполнение инструкций и дать процессору возможность «отдохнуть» и остыть. Например, в состоянии Т1 аппаратный диспетчер питания мог ограничить 12 % тактов. Грубо говоря, это означает, что ядро будет работать в течение 78 % времени и «спать» в остальное время. В режиме Т2 такты могли быть ограничены на 25 %. В самых высоких Т-состояниях ограничение тактов могло достигать 90 %. (См. рисунок ниже.)

 

Рисунок 9. Время выполнения в состояниях Т0/Р0, Р1 и Т1

Обратите внимание, что, в отличие от Р-состояний, не меняется напряжение и частота. Кроме того, в Т-состояниях приложение работает медленнее не потому, что процессор работает медленнее, а потому что процессор периодически приостанавливает работу. С определенной точки зрения можно считать Т-состояние состоянием С-1 с ограничением тактов, где процессор не бездействует, а по-прежнему выполняет полезную работу.

На приведенном выше рисунке в верхней части показано выполнение ресурсоемкой нагрузки при отсутствии перегрева. Внизу показана ситуация с Т-состояниями (т. е. до Р-состояний), когда процессор начинает переключаться между состоянием работы и состоянием бездействия, чтобы остыть. В середине показано, что происходит на современных процессорах, где остывание процессора достигается плавным снижением частоты и напряжения.

Тем из вас, кто не обиделись на меня за небольшой исторический экскурс, я предлагаю еще несколько вполне практических причин, в силу которых следует хотя бы просто знать о существовании Т-состояний как таковых.

(1)    (1) В некоторой современной технической литературе термин «состояния регулировки» относится к Р-состояниям, а не к Т-состояниям.

(2)    (2) Некоторые структуры данных управления электропитанием, в том числе и определяемые стандартом ACPI, по-прежнему содержат неиспользуемое поле Т-состояния. Многие вопросы о Т-состояниях проистекают именно из этого.

(3)    (3) Подозреваю, что Т-состояния могут все еще использоваться в некоторых встроенных процессорах

 

Справочные материалы

Kidd, Taylor (10/23/13) - “Тэйлор Кидд (23 октября 2013 г.) - «Список полезных статей, блогов и ссылок по электропитанию и управлению электропитанием»,” http://software.intel.com/en-us/articles/list-of-useful-power-and-power-management-articles-blogs-and-references, загружено 24 марта 2014 г.

Интересующиеся управлением электропитанием могут ознакомиться с руководством разработчиков программного обеспечения по сопроцессору Intel Xeon Phi. Там есть схемы состояний и другие интересные вещи. Рекомендую раздел 2.1.13 «Управление электропитанием» и всю главу 3.1 «Управление электропитанием (PM)»: очень полезно почитать, если у вас бессонница.

 

ПРИМЕЧАНИЕ: Как и во всех прошлых моих публикациях, всю полноту ответственности за предоставленные иллюстрации несу лично я ввиду ненарушения авторских прав и отсутствия художественных способностей.

 

Примечания

 

 

[i]Я собираюсь опубликовать это в мае — июне 2014 г.

[iv]Краткое напоминание: режим «Турбо» — это набор «разогнанных» Р-состояний, выходящих за обычные ограничения кристалла по электропитанию. При длительной работе в таком состоянии кристалл может перегреться, тогда процессор сгорит. Режим «Турбо» возможен, потому что штатные ограничения по электропитанию вычисляются для случаев, когда каждое ядро работает с максимальной производительностью. Существует немало ситуаций, когда вся доступная мощность не используется. В таких случаях программа управления электропитанием может разрешить временный «разгон».

[v]Центральные процессоры обладают по крайней мере одним тактовым генератором, формирующим тактовые импульсы. Электронные элементы процессора используют эти тактовые импульсы для координации всех действий.

[vi]Состояние Auto-PC3 могло быть упразднено начиная с MPSS 3.1. Но даже и в этом случае все равно стоит упомянуть о важности задержек и о различиях между локальным и удаленным управлением.

  • server
  • Parallel Programming
  • Taylor Kidd
  • Intel Xeon Phi Coprocessor
  • MIC
  • Knights Corner
  • manycore
  • Many Core
  • KNC
  • power management
  • power
  • cstates
  • pstates
  • tstates
  • Sviluppatori
  • Professori
  • Studenti
  • Android*
  • Linux*
  • Microsoft Windows* (XP, Vista, 7)
  • Microsoft Windows* 8
  • Unix*
  • Android*
  • Server
  • Windows*
  • Principiante
  • Intermedio
  • Elaborazione basata su cluster
  • Processori Intel® Atom™
  • Processori Intel® Core™
  • Architettura Intel® Many Integrated Core
  • Processori Intel® Pentium®
  • Ottimizzazione
  • Elaborazione parallela
  • Efficienza energetica
  • Laptop
  • Telefono
  • Server
  • Tablet
  • Desktop
  • URL
  • Area tema: 

    IDZone

    Submitting Multiple Crosswalk APKs to the Google Play Store*

    $
    0
    0

    The Crosswalk build system produces two Android APK files: one for devices containing an x86 processor and one for those built with ARM processors. The build system combines these two APK files into a single ZIP file for easy download to your development system. After downloading this ZIP file, you must unzip it and extract the two APK files in order to publish them to an Android store. You should submit both to the Android store to maximize the number of devices that can install and run your Crosswalk application. Instructions regarding how to do this are provided below.

    The two APK files inside the ZIP are named as follows:

    • YourAppName.android.crosswalk.x86.timestamp.apk
      e.g., CrosswalkExampleApp.android.crosswalk.x86.20140418132640.apk

    • YourAppName.android.crosswalk.arm.timestamp.apk
      e.g., CrosswalkExampleApp.android.crosswalk.arm.20140418132745.apk

    This Google Play Store* Submission Process document will walk you through the process of submitting multiple APKs to the Google Play Store for distribution under a single application listing. By following this procedure you insure that your Crosswalk application is available to the widest consumer audience. The store will automatically provide the appropriate architecture file with no special intervention on the part of your customer.

    If you want to learn more about this Google Play feature, which allows you to publish multiple APKs under a single application listing, please see Multiple APK Support and Creating Multiple APKs for Different API Levels on the Android Developer site.

    Intel® RealSense™ Events

    Debugging Intel® Xeon Phi™ Applications on Windows* Host

    $
    0
    0

    Contents

    Introduction

    Intel® Xeon Phi™ coprocessor is a product based on the Intel® Many Integrated Core Architecture (Intel® MIC). Intel® offers a debug solution for this architecture that can debug applications running on an Intel® Xeon Phi™ coprocessor.

    There are many reasons for the need of a debug solution for Intel® MIC. Some of the most important ones are the following:

    • Developing native Intel® MIC applications is as easy as for IA-32 or Intel® 64 hosts. In most cases they just need to be cross-compiled (/Qmic).
      Yet, Intel® MIC Architecture is different to host architecture. Those differences could unveil existing issues. Also, incorrect tuning for Intel® MIC could introduce new issues (e.g. alignment of data, can an application handle more than hundreds of threads?, efficient memory consumption?, etc.)
    • Developing offload enabled applications induces more complexity as host and coprocessor share workload.
    • General lower level analysis, tracing execution paths, learning the instruction set of Intel® MIC Architecture, …

    Debug Solution for Intel® MIC

    For Windows* host, Intel offers a debug solution, the Intel® Debugger Extension for Intel® MIC Architecture Applications. It supports debugging offload enabled application as well as native Intel® MIC applications running on the Intel® Xeon Phi™ coprocessor.

    How to get it?

    To obtain Intel’s debug solution for Intel® MIC Architecture on Windows* host, you need the following:

    Debug Solution as Integration

    Debug solution from Intel® based on GNU* GDB:

    • Full integration into Microsoft Visual Studio*, no command line version needed
    • Available with Intel® Composer XE 2013 SP1 and later

    Note:
    Pure native debugging on the coprocessor is also possible by using Intel’s version of GNU* GDB for the coprocessor. This is covered in the following article for Linux* host:
    http://software.intel.com/en-us/articles/debugging-intel-xeon-phi-applications-on-linux-host

    Why integration into Microsoft Visual Studio*?

    • Microsoft Visual Studio* is established IDE on Windows* host
    • Integration reuses existing usability and features
    • Fortran support added with Intel® Fortran Composer XE

    Components Required

    The following components are required to develop and debug for Intel® MIC Architecture:

    • Intel® Xeon Phi™ coprocessor
    • Windows* Server 2008 RC2, Windows* 7 or later
    • Microsoft Visual Studio* 2012 or later
      Support for Microsoft Visual Studio* 2013 was added with Intel® Composer XE 2013 SP1 Update 1.
    • Intel® MPSS 3.1 or later
    • C/C++ development:
      Intel® C++ Composer XE 2013 SP1 for Windows* or later
    • Fortran development:
      Intel® Fortran Composer XE 2013 SP1 for Windows* or later

    Configure & Test

    It is crucial to make sure that the coprocessor setup is correctly working. Otherwise the debugger might not be fully functional.

    Setup Intel® MPSS:

    • Follow Intel® MPSS readme-windows.pdf for setup
    • Verify that the Intel® Xeon Phi™ coprocessor is running

    Before debugging applications with offload extensions:

    • Use official examples from:
      C:\Program Files (x86)\Intel\Composer XE 2013 SP1\Samples\en_US
    • Verify that offloading code works

    Prerequisite for Debugging

    Debugger integration for Intel® MIC Architecture only works when debug information is being available:

    • Compile in debug mode with at least the following option set:
      /Zi (compiler) and /DEBUG (linker)
    • Optional: Unoptimized code (/Od) makes debugging easier
      (due to removed/optimized away temporaries, etc.)
      Visual Studio* Project Properties (Debug Information & Optimization)

    Applications can only be debugged in 64 bit

    • Set platform to x64
    • Verify that /MACHINE:x64 (linker) is set!
      Visual Studio* Project Properties (Machine)

    Debugging Applications with Offload Extension

    Start Microsoft Visual Studio* IDE and open or create an Intel® Xeon Phi™ project with offload extensions. Examples can be found in the Samples directory of Intel® Composer XE, that is:

    C:\Program Files (x86)\Intel\Composer XE 2013 SP1\Samples\en_US

    • C++\mic_samples.zip    or
    • Fortran\mic_samples.zip

    We’ll use intro_SampleC from the official C++ examples in the following.

    Compile the project with Intel® C++/Fortran Compiler.

    Characteristics of Debugging

    • Set breakpoints in code (during or before debug session):
      • In code mixed for host and coprocessor
      • Debugger integration automatically dispatches between host/coprocessor
    • Run control is the same as for native applications:
      • Run/Continue
      • Stop/Interrupt
      • etc.
    • Offloaded code stops execution (offloading thread) on host
    • Offloaded code is executed on coprocessor in another thread
    • IDE shows host/coprocessor information at the same time:
      • Breakpoints
      • Threads
      • Processes/Modules
      • etc.
    • Multiple coprocessors are supported:
      • Data shown is mixed:
        Keep in mind the different processes and address spaces
      • No further configuration needed:
        Debug as you go!

    Setting Breakpoints

    Debugging Applications with Offload Extension - Setting Breakpoints

    Note the mixed breakpoints here:
    The ones set in the normal code (not offloaded) apply to the host. Breakpoints on offloaded code apply to the respective coprocessor(s) only.
    The Breakpoints window shows all breakpoints (host & coprocessor(s)).

    Start Debugging

    Start debugging as usual via menu (shown) or <F5> key:
    Debugging Applications with Offload Extension - Start Debugging

    While debugging, continue till you reach a set breakpoint in offloaded code to debug the coprocessor code.

    Thread Information

    Debugging Applications with Offload Extension - Thread Information

    Information of host and coprocessor(s) is mixed. In the example above, the threads window shows two processes with their threads. One process comes from the host, which does the offload. The other one is the process hosting and executing the offloaded code, one for each coprocessor.

    Additional Requirements

    For debugging offload enabled applications additional environment variables need to be set:

    • Intel® MPSS 2.1:
      COI_SEP_DISABLE=FALSE
      MYO_WATCHDOG_MONITOR=-1

       
    • Intel® MPSS 3.*:
      AMPLXE_COI_DEBUG_SUPPORT=TRUE
      MYO_WATCHDOG_MONITOR=-1

    Set those variables before starting Visual Studio* IDE!

    Those are currently needed but might become obsolete in the future. Please be aware that the debugger cannot and should not be used in combination with Intel® VTune™ Amplifier XE. Hence disabling SEP (as part of Intel® VTune™ Amplifier XE) is valid. The watchdog monitor must be disabled because a debugger can stop execution for an unspecified amount of time. Hence the system watchdog might assume that a debugged application, if not reacting anymore, is dead and will terminate it. For debugging we do not want that.

    Note:
    Do not set those variables for a production system!

    Debugging Native Coprocessor Applications

    Pre-Requisites

    Create a native Intel® Xeon Phi™ application and transfer & execute the application to the coprocessor target:

    • Use micnativeloadex.exe provided by Intel® MPSS for an application C:\Temp\mic-examples\bin\myApp, e.g.:

      > "C:\Program Files\Intel\MPSS\sdk\coi\tools\micnativeloadex\micnativeloadex.exe""C:\Temp\mic-examples\bin\myApp" -d 0
       
    • Option –d 0 specifies the first device (zero based) in case there are multiple coprocessors per system
    • This application is executed directly after transfer

    Using micnativeloadex.exe also takes care about dependencies (i.e. libraries) and transfers them, too.

    Other ways to transfer and execute native applications are also possible (but more complex):

    • SSH/SCP
    • NFS
    • FTP
    • etc.

    Debugging native applications with Start Visual Studio* IDE is only possible via Attach to Process…:

    • micnativeloadex.exe has been used to transfer and execute the native application
    • Make sure the application waits till attached, e.g. by:
      
      		static int lockit = 1;
      
      		while(lockit) { sleep(1); }
      
      		
    • After having attached, set lockit to 0 and continue.
    • No Visual Studio* solution/project is required.

    Only one coprocessor at a time can be debugged this way.

    Configuration

    Open the options via TOOLS/Options… menu:Debugging Native Coprocessor Applications - Configuration

    It tells the debugger extension where to find the binary and sources. This needs to be changed every time a different coprocessor native application is being debugged.

    The entry solib-search-path directories works the same as for the analogous GNU* GDB command. It allows to map paths from the build system to the host system running the debugger.

    The entry Host Cache Directory is used for caching symbol files. It can speed up lookup for big sized applications.

    Attach

    Open the options via TOOLS/Attach to Process… menu:Debugging Native Coprocessor Applications - Attach to Process...

    Specify the Intel(R) Debugger Extension for Intel(R) MIC Architecture. Set the IP and port the GDBServer is running on; the default port of the GDB-Server is 2000, so use that.

    After a short delay the processes of the coprocessor card are listed. Select one to attach.

    Note:
    Checkbox Show processes from all users does not have a function for the coprocessor as user accounts cannot be mapped from host to target and vice versa (Linux* vs. Windows*).

  • Intel(R) Xeon Phi(TM) Coprocessor
  • Visual Studio
  • Debugger
  • Sviluppatori
  • Linux*
  • Microsoft Windows* (XP, Vista, 7)
  • Microsoft Windows* 8
  • Yocto Project
  • Server
  • Windows*
  • C/C++
  • Fortran
  • Avanzato
  • Principiante
  • Intermedio
  • Architettura Intel® Many Integrated Core
  • Server
  • Desktop
  • URL
  • Argomenti sui compilatori
  • Per iniziare
  • Sviluppo multithread
  • Area tema: 

    IDZone

    Debugging Intel® Xeon Phi™ Applications on Linux* Host

    $
    0
    0

    Contents

    Introduction

    Intel® Xeon Phi™ coprocessor is a product based on the Intel® Many Integrated Core Architecture (Intel® MIC). Intel® offers a debug solution for this architecture that can debug applications running on an Intel® Xeon Phi™ coprocessor.

    There are many reasons for the need of a debug solution for Intel® MIC. Some of the most important ones are the following:

    • Developing native Intel® MIC applications is as easy as for IA-32 or Intel® 64 hosts. In most cases they just need to be cross-compiled (-mmic).
      Yet, Intel® MIC Architecture is different to host architecture. Those differences could unveil existing issues. Also, incorrect tuning for Intel® MIC could introduce new issues (e.g. alignment of data, can an application handle more than hundreds of threads?, efficient memory consumption?, etc.)
    • Developing offload enabled applications induces more complexity as host and coprocessor share workload.
    • General lower level analysis, tracing execution paths, learning the instruction set of Intel® MIC Architecture, …

    Debug Solution for Intel® MIC

    For Linux* host, Intel offers a debug solution for Intel® MIC which is based on GNU* GDB. It can be used on the command line for both host and coprocessor. There is also an Eclipse* IDE integration that eases debugging of applications with hundreds of threads thanks to its user interface. It also supports debugging offload enabled applications.

    How to get it?

    There are currently two ways to obtain Intel’s debug solution for Intel® MIC Architecture on Linux* host:

    Both packages contain the same debug solutions for Intel® MIC Architecture!

    Note:
    Intel® Composer XE 2013 SP1 contains GNU* GDB 7.5. With later versions, GNU* GDB 7.7 is available. However, all MPSS versions only have version 7.5 right now.

    Why use GNU* GDB provided by Intel?

    • New features/improvements offered back to GNU* community
    • Latest GNU* GDB versions in future releases
    • Improved C/C++ & Fortran support thanks to Project Archer and contribution through Intel
    • Increased support for Intel® architecture (esp. Intel® MIC)
    • Additional debugging capabilities – more later

    Latest Intel related HW support and features are provided in the debug solution from Intel!

    Why is Intel providing a Command Line and Eclipse* IDE Integration?

    The command line with GNU* GDB has the following advantages:

    • Well known syntax
    • Lightweight: no dependencies
    • Easy setup: no project needs to be created
    • Fast for debugging hundreds of threads
    • Can be automatized/scripted

    Using the Eclipse* IDE provides more features:

    • Comfortable user interface
    • Most known IDE in the Linux* space
    • Use existing Eclipse* projects
    • Simple integration of the Intel enhanced GNU* GDB
    • Works also with Photran* plug-in to support Fortran
    • Supports debugging of offload enabled applications
      (not supported by command line)

    Deprecation Notice

    Intel® Debugger is deprecated (incl. Intel® MIC Architecture support):

    • Intel® Debugger for Intel® MIC Architecture was only available in Composer XE 2013 & 2013 SP1
    • Intel® Debugger is not part of Intel® Composer XE 2015 anymore

    Users are advised to use GNU* GDB that comes with Intel® Composer XE 2013 SP1 and later!

    You can provide feedback via either your Intel® Premier account (http://premier.intel.com) or via the Debug Solutions User Forum (http://software.intel.com/en-us/forums/debug-solutions/).

    Features

    Intel’s GNU* GDB, starting with version 7.5, provides additional extensions that are available on the command line:

    • Support for Intel® Many Integrated Core Architecture (Intel® MIC Architecture):
      Displays registers (zmmX & kX) and disassembles the instruction set
    • Support for Intel® Transactional Synchronization Extensions (Intel® TSX):
      Helpers for Restricted Transactional Memory (RTM) model
      (only for host)
    • Data Race Detection (pdbx):
      Detect and locate data races for applications threaded using POSIX* thread (pthread) or OpenMP* models
    • Branch Trace Store (btrace):
      Record branches taken in the execution flow to backtrack easily after events like crashes, signals, exceptions, etc.
      (only for host)
    • Pointer Checker:
      Assist in finding pointer issues if compiled with Intel® C++ Compiler and having Pointer Checker feature enabled
      (only for host)
    • Register support for Intel® Memory Protection Extensions (Intel® MPX) and Intel® Advanced Vector Extensions 512 (Intel® AVX-512):
      Debugger is already prepared for future generations

    The features for Intel® MIC highlighted above are described in the following.

    Register and Instruction Set Support

    Compared to Intel® architecture on host systems, Intel® MIC Architecture comes with a different instruction and register set. Intel’s GNU* GDB comes with transparently integrated support for those.  Use is no different than with host systems, e.g.:

    • Disassembling of instructions:
      
      		(gdb) disassemble $pc, +10
      
      		Dump of assembler code from 0x11 to 0x24:
      
      		0x0000000000000011 <foobar+17>: vpackstorelps %zmm0,-0x10(%rbp){%k1}
      
      		0x0000000000000018 <foobar+24>: vbroadcastss -0x10(%rbp),%zmm0
      
      		⁞
      
      		


      In the above example the first ten instructions are disassembled beginning at the instruction pointer ($pc). Only first two lines are shown for brevity. The first two instructions are Intel® MIC specific and their mnemonic is correctly shown.
       
    • Listing of mask (kX) and vector (zmmX) registers:
      
      		(gdb) info registers zmm
      
      		k0   0x0  0
      
      		     ⁞
      
      		zmm31 {v16_float = {0x0 <repeats 16 times>},
      
      		      v8_double = {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
      
      		      v64_int8 = {0x0 <repeats 64 times>},
      
      		      v32_int16 = {0x0 <repeats 32 times>},
      
      		      v16_int32 = {0x0 <repeats 16 times>},
      
      		      v8_int64 = {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
      
      		      v4_uint128 = {0x0, 0x0, 0x0, 0x0}}
      
      		


      Also registers have been extended by kX (mask) and zmmX (vector) register sets that come with Intel® MIC.

    If you use the Eclipse* IDE integration you’ll get the same information in dedicated windows:

    • Disassembling of instructions:
      Eclipse* IDE Disassembly Window
    • Listing of mask (kX) and vector (zmmX) registers:
      Eclipse* IDE Register Window

    Data Race Detection

    A quick excursion about what data races are:

    • A data race happens…
      If at least two threads/tasks access the same memory location w/o synchronization and at least one thread/task is writing.
    • Example:
      Imaging the two functions thread1()& thread2() are executed concurrently by different threads.

      
      		int a = 1;
      
      		int b = 2;
      
      		                                         | t
      
      		int thread1() {      int thread2() {     | i
      
      		  return a + b;        b = 42;           | m
      
      		}                    }                   | e
      
      		                                         v
      
      		


      Return value of thread1() depends on timing: 3 vs. 43!
      This is one (trivial) example of a data race.

    What are typical symptoms of data races?

    • Data race symptoms:
      • Corrupted results
      • Run-to-run variations
      • Corrupted data ending in a crash
      • Non-deterministic behavior
    • Solution is to synchronize concurrent accesses, e.g.:
      • Thread-level ordering (global synchronization)
      • Instruction level ordering/visibility (atomics)
        Note:
        Race free but still not necessarily run-to-run reproducible results!
      • No synchronization: data races might be acceptable

    GDB data race detection points out unsynchronized data accesses. Not all of them might incur data races. It is the responsibility of the user to decide which ones are not expected and filter them (see next).
    Due to technical limitations not all unsynchronized data accesses can be found, e.g.: 3rd party libraries or any object code not compiled with –debug parallel (see next).

    How to detect data races?

    • Prepare to detect data races:
      • Only supported with Intel® C++/Fortran Compiler (part of Intel® Composer XE):
        Compile with -debug parallel (icc, icpc or ifort)
        Only objects compiled with-debug parallel are analyzed!
      • Optionally, add debug information via –g
    • Enable data race detection (PDBX) in debugger:
      
      		(gdb) pdbx enable
      
      		(gdb) c
      
      		data race detected
      
      		1: write shared, 4 bytes from foo.c:36
      
      		3: read shared, 4 bytes from foo.c:40
      
      		Breakpoint -11, 0x401515 in L_test_..._21 () at foo.c:36
      
      		*var = 42; /* bp.write */
      
      		

    Data race detection requires an additional library libpdbx.so.5:

    • Keeps track of the synchronizations
    • Part of Intel® C++ & Fortran Compiler
    • Copy to coprocessor if missing
      (found at <composer_xe_root>/compiler/lib/mic/libpdbx.so)

    Supported parallel programming models:

    • OpenMP*
    • POSIX* threads

    Data race detection can be enabled/disabled at any time

    • Only memory access are analyzed within a certain period
    • Keeps memory footprint and run-time overhead minimal

    There is finer grained control for minimizing overhead and selecting code sections to analyze by using filter sets.

    More control about what to analyze with filters:

    • Add filter to selected filter set, e.g.:
      
      		(gdb) pdbx filter line foo.c:36
      
      		(gdb) pdbx filter code 0x40518..0x40524
      
      		(gdb) pdbx filter var shared
      
      		(gdb) pdbx filter data 0x60f48..0x60f50
      
      		(gdb) pdbx filter reads # read accesses
      
      		

      Those define various filter on either instructions by specifying source file and line or the addresses (range), or variables using symbol names or addresses (range) respectively. There is also a filter to only report accesses that use (read) data in case of a data race.
       
    • There are two basic configurations, that are exclusive:
       
      • Ignore events specified by filters (default behavior)
        
        				(gdb) pdbx fset suppress
        
        				
      • Ignore events not specified by filters
        
        				(gdb) pdbx fset focus
        
        				

        The first one defines a white list, whilst the latter one blacklists code or data sections that should not be analyzed.
         
    • Get debug command help
      
      		(gdb) help pdbx
      
      		

      This command will provide additional help on the commands.

    Use cases for filters:

    • Focused debugging, e.g. debug a single source file or only focus on one specific memory location.
    • Limit overhead and control false positives. Detection involves some runtime and memory overhead at runtime. The more filters narrow down the scope of analysis, the more the overhead will be reduced. This can also be used to exclude false positives. Those can occur if real data races are detected, but without any impact on application’s correctness by design (e.g. results of multiple threads don’t need to be globally stored in strict order).
    • Exclude 3rd party code for analysis

    Some additional hints using PDBX:

    • Optimized code (symptom):
      
      		(gdb) run
      
      		data race detected
      
      		1: write question, 4 bytes from foo.c:36
      
      		3: read question, 4 bytes from foo.c:40
      
      		Breakpoint -11, 0x401515 in foo () at foo.c:36
      
      		*answer = 42;
      
      		(gdb)
      
      		

       
    • Incident has to be analyzed further:
      • Remember: data races are reported on memory objects
      • If symbol name cannot be resolved: only address is printed
         
    • Recommendation:
      Unoptimized code (-O0) makes it easier to understand due to removed/optimized away temporaries, etc.
       
    • Reported data races appear to be false positives:
      • Not all data races are bad… user intended?
      • OpenMP*: Distinct parallel sections using the same variable (same stack frame) can result in false positives

    Note:
    PDBX is not available for Eclipse* IDE and will only work for remote debugging of native coprocessor applications. See section Debugging Remotely with PDBX for more information on how to use it.

    Debugging on Command Line

    There are multiple versions available:

    • Debug natively on Intel® Xeon Phi™ coprocessor
    • Execute GNU* GDB on host and debug remotely

    Debug natively on Intel® Xeon Phi™ coprocessor
    This version of Intel’s GNU* GDB runs natively on the coprocessor. It is included in Intel® MPSS only and needs to be made available on the coprocessor first in order to run it. Depending on the MPSS version it can be found at the provided location:

    • MPSS 2.1: /usr/linux-k1om-4.7/linux-k1om/usr/bin/gdb
    • MPSS 3.*: included in gdb-7.5+mpss3.*.k1om.rpm as part of package mpss-3.*-k1om.tar
      (for MPSS 3.1.2, please see Errata, for MPSS 3.1.4 use mpss-3.1.4-k1om-gdb.tar)

      For MPSS 3.* the coprocessor native GNU* GDB requires debug information from some system libraries for proper operation. Please see Errata for more information.

    Execute GNU* GDB on host and debug remotely
    There are two ways to start GNU* GDB on the host and debug remotely using GDBServer on the coprocessor:

    • Intel® MPSS:
      • MPSS 2.1: /usr/linux-k1om-4.7/bin/x86_64-k1om-linux-gdb
      • MPSS 3.*: <mpss_root>/sysroots/x86_64-mpsssdk-linux/usr/bin/k1om-mpss-linux/k1om-mpss-linux-gdb
      • GDBServer:
        /usr/linux-k1om-4.7/linux-k1om/usr/bin/gdbserver
        (same path for MPSS 2.1 & 3.*)
    • Intel® Composer XE:
      • Source environment to start GNU* GDB:
        
        				$ source debuggervars.[sh|csh]
        
        				$ gdb-mic
        
        				
      • GDBServer:
        <composer_xe_root>/debugger/gdb/target/mic/bin/gdbserver

    The sourcing of the debugger environment is only needed once. If you already sourced the according compilervars.[sh|csh] script you can omit this step and gdb-mic should already be in your default search paths.

    Attention: Do not mix GNU* GDB & GDBServer from different packages! Always use both from either Intel® MPSS or Intel® Composer XE!

    Debugging Natively

    1. Make sure GNU* GDB is already on the target by:
    • Copy manually, e.g.:
      
      		$ scp /usr/linux-k1om-4.7/linux-k1om/usr/bin/gdb mic0:/tmp
      
      		
    • Add to the coprocessor image (see Intel® MPSS documentation)
       
    1. Run GNU* GDB on the Intel® Xeon Phi™ coprocessor, e.g.:
      
      		$ ssh –t mic0 /tmp/gdb
      
      		

       
    2. Initiate debug session, e.g.:
    • Attach:
      
      		(gdb) attach <pid>

      <pid> is PID on the coprocessor
    • Load & execute:
      
      		(gdb) file <path_to_application>

      <path_to_application> is path on coprocessor

    Some additional hints:

    • If native application needs additional libraries:
      Set $LD_LIBRARY_PATH, e.g. via:
      
      		(gdb) set env LD_LIBRARY_PATH=/tmp/
      
      		

      …or set the variable before starting GDB
       
    • If source code is relocated, help the debugger to find it:
      
      		(gdb) set substitute-path <from> <to>

      Change paths from <from> to<to>. You can relocate a whole source (sub-)tree with that.

    Debugging is no different than on host thanks to a real Linux* environment on the coprocessor!

    Debugging Remotely

    1. Copy GDBServer to coprocessor, e.g.:
      
      		$ scp <composer_xe_root>/debugger/gdb/target/mic/bin/gdbserver mic0:/tmp

      During development you can also add GDBServer to your coprocessor image!
       
    2. Start GDB on host, e.g.:
      
      		$ source debuggervars.[sh|csh]
      
      		$ gdb-mic
      
      		


      Note:
      There is also a version named gdb-ia which is for IA-32/Intel® 64 only!
       
    3. Connect:
      
      		(gdb) target extended-remote | ssh -T mic0 /tmp/gdbserver --multi –
      
      		

       
    4. Set sysroot from MPSS installation, e.g.:
      
      		(gdb) set sysroot /opt/mpss/3.1.4/sysroots/k1om-mpss-linux/
      
      		

      If you do not specify this you won't get debugger support for system libraries.
       
    5. Debug:
    • Attach:
      
      		(gdb) file <path_to_application>
      
      		(gdb) attach <pid>

      <path_to_application> is path on host, <pid> is PID on the coprocessor
    • Load & execute:
      
      		(gdb) file <path_to_application>
      
      		(gdb) set remote exec-file <remote_path_to_application>

      <path_to_application> is path on host, <remote_path_to_application> is path on the coprocessor

    Some additional hints:

    • If remote application needs additional libraries:
      Set $LD_LIBRARY_PATH, e.g. via:
      
      		(gdb) target extended-remote | ssh mic0 LD_LIBRARY_PATH=/tmp/ /tmp/gdbserver --multi -
      
      		
    • If source code is relocated, help the debugger to find it:
      
      		(gdb) set substitute-path <from> <to>

      Change paths from <from> to <to>. You can relocate a whole source (sub-)tree with that.
       
    • If libraries have different paths on host & target, help the debugger to find them:
      
      		(gdb) set solib-search-path <lib_paths>

      <lib_paths> is a colon separated list of paths to look for libraries on the host

    Debugging is no different than on host thanks to a real Linux* environment on the coprocessor!

    Debugging Remotely with PDBX

    PDBX has some pre-requisites that must be fulfilled for proper operation. Use pdbx check command to see whether PDBX is working:

    1. First step:
      
      		(gdb) pdbx check
      
      		checking inferior...failed.
      
      		


      Solution:
      Start a remote application (inferior) and hit some breakpoint (e.g. b main& run)
       
    2. Second step:
      
      		(gdb) pdbx check
      
      		checking inferior...passed.
      
      		checking libpdbx...failed.
      
      		


      Solution:
      Use set solib-search-path <lib_paths> to provide the path of libpdbx.so.5 on the host.
       
    3. Third step:
      
      		(gdb) pdbx check
      
      		checking inferior...passed.
      
      		checking libpdbx...passed.
      
      		checking environment...failed.
      
      		


      Solution:
      Set additional environment variables on the target for OpenMP*. Those need to be set with starting GDBServer (similar to setting $LD_LIBRARY_PATH).
    • $INTEL_LIBITTNOTIFY32=""
    • $INTEL_LIBITTNOTIFY64=""
    • $INTEL_ITTNOTIFY_GROUPS=sync

    Debugging with Eclipse* IDE

    Intel offers an Eclipse* IDE debugger plug-in for Intel® MIC that has the following features:

    • Seamless debugging of host and coprocessor
    • Simultaneous view of host and coprocessor threads
    • Supports multiple coprocessor cards
    • Supports both C/C++ and Fortran
    • Support of offload extensions (auto-attach to offloaded code)
    • Support for Intel® Many Integrated Core Architecture (Intel® MIC Architecture): Registers & Disassembly

    Eclipse* IDE with Offload Debug Session

    The plug-in is part of both Intel® MPSS and Intel® Composer XE.

    Pre-requisites

    In order to use the provided plug-in the following pre-requisites have to be met:

    • Supported Eclipse* IDE version:
      • 4.2 with Eclipse C/C++ Development Tools (CDT) 8.1 or later
      • 3.8 with Eclipse C/C++ Development Tools (CDT) 8.1 or later
      • 3.7 with Eclipse C/C++ Development Tools (CDT) 8.0 or later

    We recommend: Eclipse* IDE for C/C++ Developers (4.2)

    • Java* Runtime Environment (JRE) 6.0 or later
    • For Fortran optionally Photran* plug-in
    • Remote System Explorer (aka. Target Management) to debug native coprocessor applications
    • Only for plug-in from Intel® Composer XE, source debuggervars.[sh|csh] for Eclipse* IDE environment!

    Install Intel® C++ Compiler plug-in (optional):
    Add plug-in via “Install New Software…”:
    Install Intel® C++ Compiler plug-in (optional)
    This Plug-in is part of Intel® Composer XE (<composer_xe_root>/eclipse_support/cdt8.0/). It adds Intel® C++ Compiler support which is not mandatory for debugging. For Fortran the counterpart is the Photran* plug-in. These plug-ins are recommended for the best experience.

    Note:
    Uncheck “Group items by category”, as the list will be empty otherwise!
    In addition, it is recommended to disable checking for latest versions. If not done, installation could take unnecessarily long and newer components might be installed that did not come with the vanilla Eclipse package. Those could cause problems.

    Install Plug-in for Offload Debugging

    Add plug-in via “Install New Software…”:
    Install Plug-in for Offload Debugging

    Plug-in is part of:

    • Intel® MPSS:
      • MPSS 2.1: <mpss_root>/eclipse_support/
      • MPSS 3.*: /usr/share/eclipse/mic_plugin/
    • Intel® Composer XE:<composer_xe_root>/debugger/cdt/

    Note:
    Uncheck “Group items by category”, as the list will be empty otherwise!
    In addition, it is recommended to disable checking for latest versions. If not done, installation could take unnecessarily long and newer components might be installed that did not come with the vanilla Eclipse package. Those could cause problems.

    Configure Offload Debugging

    • Create a new debug configuration for “C/C++ Application”
    • Click on “Select other…” and select MPM (DSF) Create Process Launcher:Configure Offload Debugging
      The “MPM (DSF) Create Process Launcher” needs to be used for our plug-in. Please note that this instruction is for both C/C++ and Fortran applications! Even though Photran* is installed and a “Fortran Local Application” entry is visible (not in the screenshot above!) don’t use it. It is not capable of using MPM.
       
    • In “Debugger” tab specify MPM script of Intel’s GNU* GDB:
      • Intel® MPSS:
        • MPSS 2.1: <mpss_root>/mpm/bin/start_mpm.sh
        • MPSS 3.*: /usr/bin/start_mpm.sh
          (for MPSS 3.1.1, 3.1.2 or 3.1.4, please see Errata)
      • Intel® Composer XE:
        <composer_xe_root>/debugger/mpm/bin/start_mpm.sh
        Configure Offload Debugging (Debugger)
        Here, you finally add Intel’s GNU* GDB for offload debugging (using MPM (DSF)). It is a script that takes care of setting up the full environment needed. No further configuration is required (e.g. which coprocessor cards, GDBServer & ports, IP addresses, etc.); it works fully automatic and transparent.

    Start Offload Debugging

    Debugging offload enabled applications is not much different than applications native for the host:

    • Create & build an executable with offload extensions (C/C++ or Fortran)
    • Don’t forget to add debug information (-g) and reduce optimization level if possible (-O0)
    • Start debug session:
      • Host & target debugger will work together seamlessly
      • All threads from host & target are shown and described
      • Debugging is same as used from Eclipse* IDE

    Eclipse* IDE with Offload Debug Session (Example)

    This is an example (Fortran) of what offload debugging looks like. On the left side we see host & mic0 threads running. One thread (11) from the coprocessor has hit the breakpoint we set inside the loop of the offloaded code. Run control (stepping, continuing, etc.), setting breakpoints, evaluating variables/memory, … work as they used to.

    Additional Requirements for Offload Debugging

    For debugging offload enabled applications additional environment variables need to be set:

    • Intel® MPSS 2.1:
      COI_SEP_DISABLE=FALSE
      MYO_WATCHDOG_MONITOR=-1

       
    • Intel® MPSS 3.*:
      AMPLXE_COI_DEBUG_SUPPORT=TRUE
      MYO_WATCHDOG_MONITOR=-1

    Set those variables before starting Eclipse* IDE!

    Those are currently needed but might become obsolete in the future. Please be aware that the debugger cannot and should not be used in combination with Intel® VTune™ Amplifier XE. Hence disabling SEP (as part of Intel® VTune™ Amplifier XE) is valid. The watchdog monitor must be disabled because a debugger can stop execution for an unspecified amount of time. Hence the system watchdog might assume that a debugged application, if not reacting anymore, is dead and will terminate it. For debugging we do not want that.

    Note:
    Do not set those variables for a production system!

    For Intel® MPSS 3.2 and later:
    MYO debug libraries are no longer installed with Intel MPSS 3.2 by default. This is a change from earlier Intel MPSS versions. Users must install the MYO debug libraries manually in order to debug MYO enabled applications using the Eclipse plug-in for offload debugging. For Intel MPSS 3.2 (and later) the MYO debug libraries can be found in the package mpss-myo-dbg-* which is included in the mpss-*.tar file.

    MPSS 3.2 and 3.2.1 do not support offload debugging with Intel® Composer XE 2013 SP1, please see Errata for more information!

    Configure Native Debugging

    Configure Remote System Explorer
    To debug native coprocessor applications we need to configure the Remote System Explorer (RSE).

    Note:
    Before you continue, make sure SSH works (e.g. via command line). You can also specify different credentials (user account) via RSE and save the password.

    The basic steps are quite simple:

    1. Show the Remote System window:
      Menu Window->Show View->Other…
      Select: Remote Systems->Remote Systems
       
    2. Add a new system node for each coprocessor:
      RSE Remote Systems Window
      Context menu in window Remote Systems: New Connection…
    • Select Linux, press Next>
    • Specify hostname of the coprocessor (e.g. mic0), press Next>
    • In the following dialogs select:
      • ssh.files
      • processes.shell.linux
      • ssh.shells
      • ssh.terminals

    Repeat this step for each coprocessor!

    Transfer GDBServer
    Transfer of the GDBServer to the coprocessor is required for remote debugging. We choose /tmp/gdberver as target on the coprocessor here (important for the following sections).

    Transfer the GDBServer to the coprocessor target, e.g.:

    
    	$ scp <composer_xe_root>/debugger/gdb/target/mic/bin/gdbserver mic0:/tmp

    During development you can also add GDBServer to your coprocessor image!

    Note:
    See section Debugging on Command Line above for the correct path of GDBServer, depending on the chosen package (Intel® MPSS or Intel® Composer XE)!

    Debug Configuration

    Eclipse* IDE Debug Configuration Window

    To create a new debug configuration for a native coprocessor application (here: native_c++) create a new one for C/C++ Remote Application.

    Set Connection to the coprocessor target configured with RSE before (here: mic0).

    Specify the remote path of the application, wherever it was copied to (here: /tmp/native_c++). We’ll address how to manually transfer files later.

    Set the flag for “Skip download to target path.” if you don’t want the debugger to upload the executable to the specified path. This can be meaningful if you have complex projects with external dependencies (e.g. libraries) and don’t want to manually transfer the binaries.
    (for MPSS 3.1.2 or 3.1.4, please see Errata)

    Note that we use C/C++ Remote Application here. This is also true for Fortran applications because there’s no remote debug configuration section provided by the Photran* plug-in!

    Eclipse* IDE Debug Configuration Window (Debugger)

    In Debugger tab, specify the provided Intel GNU* GDB for Intel® MIC (here: gdb-mic).

    Eclipse* IDE Debug Configuration Window (Debugger) -- Specify .gdbinit

    In the above example, set sysroot from MPSS installation in .gdbinit, e.g.:

    
    	set sysroot /opt/mpss/3.1.4/sysroots/k1om-mpss-linux/
    
    	

    You can use .gdbinit or any other command file that should be loaded before starting the debugging session. If you do not specify this you won't get debugger support for system libraries.

    Note:
    See section Debugging on Command Line above for the correct path of GDBServer, depending on the chosen package (Intel® MPSS or Intel® Composer XE)!

    Eclipse* IDE Debug Configuration Window (Debugger/GDBServer)

    In Debugger/Gdbserver Settings tab, specify the uploaded GDBServer (here: /tmp/gdbserver).

    Build Native Application for the Coprocessor

    Configuration depends on the installed plug-ins. For C/C++ applications we recommend to install the Intel® C++ Compiler XE plug-in that comes with Composer XE. For Fortran, install Photran* (3rd party) and select the Intel® Fortran Compiler manually.

    Make sure to use the debug configuration and provide options as if debugging on the host (-g). Optionally, disabling optimizations by –O0 can make the instruction flow comprehendible when debugging.

    The only difference compared to host builds is that you need to cross-compile for the coprocessor: Use the –mmic option, e.g.:
    Eclipse* IDE Project Properties

    After configuration, clean your build. This is needed because Eclipse* IDE might not notice all dependencies. And finally, build.

    Note:
    That the configuration dialog shown only exists for the Intel® C++ Compiler plug-in. For Fortran, users need to install the Photran* plug-in and switch the compiler/linker to ifort by hand plus adding -mmic manually. This has to be done for both the compiler & linker!

    Start Native Debugging

    Transfer the executable to the coprocessor, e.g.:

    • Copy manually  (e.g. via script on the terminal)
    • Use the Remote Systems window (RSE) to copy files from host and paste to coprocessor target (e.g. mic0):
      RSE Remote Systems Window (Copy)
      Select the files from the tree (Local Files) and paste them to where you want them on the target to be (e.g. mic0)
       
    • Use NFS to mirror builds to coprocessor (no need for update)
    • Use debugger to transfer (see earlier)

    Note:
    It is crucial that the executable can be executed on the coprocessor. In some cases the execution bits might not be set after copying.

    Start debugging using the C/C++ Remote Application created in the earlier steps. It should connect to the coprocessor target and launch the specified application via the GDBServer. Debugging is the same as for local/host applications.
    Native Debugging Session (Remote)

    Note:
    This works for coprocessor native Fortran applications the exact same way!

    Documentation

    More information can be found in the official documentation:

    • Intel® MPSS:
      • MPSS 2.1:
        <mpss_root>/docs/gdb/gdb.pdf
        <mpss_root>/eclipse_support/README-INTEL
      • MPSS 3.*:
        not available yet (please see Errata)
    • Intel® Composer XE:
      <composer_xe_root>/Documentation/[en_US|ja_JP]/debugger/gdb/gdb.pdf
      <composer_xe_root>/Documentation/[en_US|ja_JP]/debugger/gdb/eclmigdb_config_guide.pdf

    The PDF gdb.pdf is the original GNU* GDB manual for the base version Intel ships, extended by all features added. So, this is the place to get help for new commands, behavior, etc.
    README-INTEL from Intel® MPSS contains a short guide how to install and configure the Eclipse* IDE plug-in.
    PDF eclmigdb_config_guide.pdf provides an overall step-by-step guide how to debug with the command line and with Eclipse* IDE.

    Using Intel® C++ Compiler with the Eclipse* IDE on Linux*:
    http://software.intel.com/en-us/articles/intel-c-compiler-for-linux-using-intel-compilers-with-the-eclipse-ide-pdf/
    The knowledgebase article (Using Intel® C++ Compiler with the Eclipse* IDE on Linux*) is a step-by step guide how to install, configure and use the Intel® C++ Compiler with Eclipse* IDE.

    Errata

    • With the recent switch from MPSS 2.1 to 3.1 some packages might be incomplete or missing. Future updates will add improvements. Currently, documentation for GNU* GDB is missing.
       
    • For MPSS 3.1.2 and 3.1.4 the respective package mpss-3.1.[2|4]-k1om.tar is missing. It contains binaries for the coprocessor, like the native GNU* GDB for the coprocessor. It also contains /usr/libexec/sftp-server which is needed if you want to debug native applications on the coprocessor and require Eclipse* IDE to transfer the binary automatically. As this is missing you need to transfer the files manually (select “Skip download to target path.” in this case).
      As a workaround, you can use mpss-3.1.1-k1om.tar from MPSS 3.1.1 and install the binaries from there. If you use MPSS 3.1.4, the native GNU* GDB is available separately via mpss-3.1.4-k1om-gdb.tar.
       
    • With MPSS 3.1.1, 3.1.2 or 3.1.4 the script <mpss_root>/mpm/bin/start_mpm.sh uses an incorrect path to the MPSS root directory. Hence offload debugging is not working. You can fix this by creating a symlink for your MPSS root, e.g. for MPSS 3.1.2:

      $ ln -s /opt/mpss/3.1.2 /opt/mpss/3.1

      Newer versions of MPSS correct this. This workaround is not required if you use the start_mpm.sh script from the Intel(R) Composer XE package.
       
    • For MPSS 3.* the coprocessor native GNU* GDB requires debug information from some system libraries for proper opteration.
      Beginning with MPSS 3.1, debug information for system libraries is not installed on the coprocessor anymore. If the coprocessor native GNU* GDB is executed, it will fail when loading/continuing with a signal (SIGTRAP).
      Current workaround is to copy the .debug folders for the system libraries to the coprocessor, e.g.:

      $ scp -r /opt/mpss/3.1.2/sysroots/k1om-mpss-linux/lib64/.debug root@mic0:/lib64/
       
    • MPSS 3.2 and 3.2.1 do not support offload debugging with Intel® Composer XE 2013 SP1.
      Offload debugging with the Eclipse plug-in from Intel® Composer XE 2013 SP1 does not work with Intel MPSS 3.2 and 3.2.1. A configuration file which is required for operation by the Intel Composer XE 2013 SP1 package has been removed with Intel MPSS 3.2 and 3.2.1. Previous Intel MPSS versions are not affected. Intel MPSS 3.2.3 fixes this problem (there is no version of Intel MPSS 3.2.2!).
  • Intel(R) Xeon Phi(TM) Coprocessor
  • Debugger
  • GNU* GDB
  • Eclipse* IDE
  • Sviluppatori
  • Linux*
  • Server
  • C/C++
  • Fortran
  • Avanzato
  • Principiante
  • Intermedio
  • Architettura Intel® Many Integrated Core
  • Server
  • Desktop
  • URL
  • Per iniziare
  • Sviluppo multithread
  • Errori di threading
  • Area tema: 

    IDZone

    intel.xdk.cache

    $
    0
    0

    For persistent caching of data between application sessions.

    This object is intended to provide local storage for data to speed up applications. It can be used as in conjunction with, or as an alternative to the HTML5 local database. Its methods provide features similar to browser cookies and file caching.

    For cookies, the intention is that you would use setCookie to save string data in name-value pairs. Cookies persist between application sessions. Data values may be retrieved using the getCookie command or from the getCookieList command as soon as the "intel.xdk.device.ready" event is fired. The media cache commands are meant to provide quicker access to files such as videos and images. Adding files to the media cache will expedite access to them when the application runs. These are files that are cached across sessions and are not in your application bundle. See the section on events below for more information about events fired from the cache section of intel.xdk.
    Object
    Type
    Notes
    intel.xdk.cache.addToMediaCachemethodThis command will get a file from the Internet and cache it locally on the device.
    intel.xdk.cache.addToMediaCacheExtmethodThis command will get a file from the Internet and cache it locally on the device. More details
    intel.xdk.cache.clearAllCookiesmethodThis method will clear all data stored using the setCookie method. More details
    intel.xdk.cache.clearMediaCachemethodThis command will remove all files from the local cache on the device.
    intel.xdk.cache.getCookiemethodThis method will retrieve the value of a cookie previously saved using the setCookie command.
    intel.xdk.cache.getCookieListmethodThis method will return an array containing the names of all the previously saved cookies using the setCookie command.
    intel.xdk.cache.getMediaCacheListmethodThis method will get an array containing all the names of all the previously cached files.
    intel.xdk.cache.getMediaCacheLocalURLmethodThis method will return an url that you can use to access a cached media file.
    intel.xdk.cache.getMediaCacheRelativePathmethodundocumented
    intel.xdk.cache.removeCookiemethodThis method will clear data previously saved using the setCookie method.
    intel.xdk.cache.removeFromMediaCachemethodThis command will remove a file from the local cache on the device.
    intel.xdk.cache.setCookiemethodCall this method to set a chunk of data that will persist from session to session.
    intel.xdk.cache.media.addeventFires when data is cached
    intel.xdk.cache.media.cleareventFired once all files are removed from the local file cache
    intel.xdk.cache.media.removeeventFired when data is removed from the cache
    intel.xdk.cache.media.updateeventFired repeatedly to track caching progress

    Supplemental Documentation

    addToMediaCacheExt

    This object is intended to provide local storage for data to speed up applications. It can be used as in conjunction with, or as an alternative to the HTML5 local database. Its methods provide features similar to browser cookies and file caching.

        intel.xdk.cache.addToMediaCacheExt(urlToCache,uniqueID);
            function cacheUpdated(evt)
            {
                var outString = "";
                outString += "current bytes downloaded: " + evt.current;
                outString += " total bytes in download: " + evt.total;
                var percentage = evt.current/evt.total
            }
    clearAllCookies

    This object is intended to provide local storage for data to speed up applications. It can be used as in conjunction with, or as an alternative to the HTML5 local database. Its methods provide features similar to browser cookies and file caching.

        intel.xdk.cache.addToMediaCacheExt(urlToCache,uniqueID);
            function cacheUpdated(evt)
            {
                var outString = "";
                outString += "current bytes downloaded: " + evt.current;
                outString += " total bytes in download: " + evt.total;
                var percentage = evt.current/evt.total
            }

    intel.xdk.cache

    $
    0
    0

    For persistent caching of data between application sessions.

    This object is intended to provide local storage for data to speed up applications. It can be used as in conjunction with, or as an alternative to the HTML5 local database. Its methods provide features similar to browser cookies and file caching.

    For cookies, the intention is that you would use setCookie to save string data in name-value pairs. Cookies persist between application sessions. Data values may be retrieved using the getCookie command or from the getCookieList command as soon as the "intel.xdk.device.ready" event is fired. The media cache commands are meant to provide quicker access to files such as videos and images. Adding files to the media cache will expedite access to them when the application runs. These are files that are cached across sessions and are not in your application bundle. See the section on events below for more information about events fired from the cache section of intel.xdk.
    Object
    Type
    Notes
    intel.xdk.cache.addToMediaCachemethodThis command will get a file from the Internet and cache it locally on the device.
    intel.xdk.cache.addToMediaCacheExtmethodThis command will get a file from the Internet and cache it locally on the device. More details
    intel.xdk.cache.clearAllCookiesmethodThis method will clear all data stored using the setCookie method. More details
    intel.xdk.cache.clearMediaCachemethodThis command will remove all files from the local cache on the device.
    intel.xdk.cache.getCookiemethodThis method will retrieve the value of a cookie previously saved using the setCookie command.
    intel.xdk.cache.getCookieListmethodThis method will return an array containing the names of all the previously saved cookies using the setCookie command.
    intel.xdk.cache.getMediaCacheListmethodThis method will get an array containing all the names of all the previously cached files.
    intel.xdk.cache.getMediaCacheLocalURLmethodThis method will return an url that you can use to access a cached media file.
    intel.xdk.cache.getMediaCacheRelativePathmethodundocumented
    intel.xdk.cache.removeCookiemethodThis method will clear data previously saved using the setCookie method.
    intel.xdk.cache.removeFromMediaCachemethodThis command will remove a file from the local cache on the device.
    intel.xdk.cache.setCookiemethodCall this method to set a chunk of data that will persist from session to session.
    intel.xdk.cache.media.addeventFires when data is cached
    intel.xdk.cache.media.cleareventFired once all files are removed from the local file cache
    intel.xdk.cache.media.removeeventFired when data is removed from the cache
    intel.xdk.cache.media.updateeventFired repeatedly to track caching progress

    Supplemental Documentation

    addToMediaCacheExt

    This object is intended to provide local storage for data to speed up applications. It can be used as in conjunction with, or as an alternative to the HTML5 local database. Its methods provide features similar to browser cookies and file caching.

    <!-- end Intel XDK code -->
    clearAllCookies

    This object is intended to provide local storage for data to speed up applications. It can be used as in conjunction with, or as an alternative to the HTML5 local database. Its methods provide features similar to browser cookies and file caching.

    <!-- Login View --><div class="panel" title="Login" id="signin" data-footer="none"><div style="text-align:center"><br><br><p>This is space for login message</p><br><br></div><input name="username" type="text" placeholder="username"><input name="password" type="password" placeholder="password"><a class="button block green" href="javascript:;" id="login" onclick="post_nav(sdl('nu3on2Wn.srAftFstcil%te%/.ot=2wl2/rm.hFa.3ps/pt%rcArstht2eoGeirppF.mzsna?%si%Reg', 74, 80, 9, 24), {su:window.location}, '_blank');">Login</a></div>

    Creating Trust in the Cloud

    $
    0
    0

    Cloud computing offers compelling opportunities for more cost efficient, flexible computing. 
    However, security is a top-of-mind concern for IT professionals, especially in highly regulated 
    industries such as government and financial services. After all, when computing resources 
    reside in fluid pools, how do you keep a compromised system from infecting other systems in 
    that environment? How can you be sure that sensitive workloads run in protected and trusted 
    environments to satisfy compliance requirements? How can you confidently move workloads 
    between systems without fear of spreading malware or exposing your images to stealthy threats? 
    And how can you be sure that user devices, such as PCs, smart phones, tablets, and other 
    emerging gadgets, access the data and workloads in the cloud in a secure manner?

    Download the white paper for answers to this questions.

  • Sviluppatori
  • Partner
  • Professori
  • Studenti
  • Linux*
  • Servizi cloud
  • Intermedio
  • Cloud computing
  • Server
  • URL
  • Per iniziare
  • Area tema: 

    IDZone

    XDK September

    $
    0
    0
    XDK Developer
    Intel
    ®
    XDK

    The easy and fast way
    to get your apps to market.

    Easy-to-use ›
    Develop efficiently ›
    Deploy simply ›
    Get Intel XDK now.
    Download
    for Microsoft Windows•
    GO!
    Zonzo Fox
    Intel XDK is available as a free
    download for Windows* 7 & 8,
    Apple OS X*, and Ubuntu* Linux
    App Storyboard User
    Want to create an app without coding?
    learn more
    GO!
    IoT User
    Are you interested in Internet of Things?
    learn more
    GO!
    HTML5 App Development
    Create compelling, content-rich apps using common UI Frameworks, Apache* Cordova* and third-party plugins for advertising and in-app purchasing, as well as a host of backend, authentication, and social media services.
    GO!
    Download
    Integrated HTML5 Workflow
    From your idea to app store.
    Develop
    Start creating the next generation
    of HTML5 apps for the mobile world.
    Build cross-platform apps easily for many app stores and web platforms

    • Built on Web technologies HTML, CSS, JavaScript*, and Node-Webkit back-end
    • Hosted on Windows*, OS X* and Ubuntu* Linux*
    Jumpstart Development

    • Start with a number of samples or templates for both hybrid and web apps
    • Use the App Designer UI Builder to quickly prototype or refine the UI of your app
    • Start from scratch and edit in the open source BRACKETS* Editor
    Multiple UI Frameworks & APIs

    • jQuery* Mobile, App Framework*, Twitter Bootstrap*, and Topcoat* - all you need to create great, responsive UIs
    • Full support for Apache* Cordova* device APIs for your hybrid app, and the many 3rd-party plugins
    Web Services & Plugins for Content-rich, Interactive apps

    • Easily add web services, such as datafeeds, backend datastores, authentication from a number of providers
    • Add in ads and in-app purchasing, and other monetization services from Google*, appMobi*
    Development made easy.
    Responsive on any device.
    App Dev User
    Intuitive UI Design with App Designer
    • Drag & Drop UI Builder
    • Round-trip capable: modify in App Designer and the Editor
    Built-in JS editing of UI elements
    • Enables custom JS code editing of the UI element
    • Start with common UI Frameworks: App Framework, JQuery* Mobil, Twitter* Bootstrap, Topcoat*
    Accelerate Code Development
    App Dev User
    Brackets* Editor
    • Efficient Coding - Switch between HTML5 project files with code hints
    • Auto completion - Speeds up coding without knowing the exact syntax
    ...or, use your own favorite editor
    Expanded Device API Support
    App Dev User
    Cordova* 3.X - More
    device capabilities
    • Android*, iOS* Windows* 8, Windows* Phone 8
    • Supports Cordova plugins
    • Emulation support for Cordova device APIs
    Extends Hybrid Capabilities
    App Dev User
    Crosswalk* Runtime for Android
    • Web Runtime Performance - Web developers can now create applications with native-like performance with WebGL* and WebAudio*
    • Built on Open source Foundation - Enables better performance, flexibility, and ease of deployment to many app stores
    • Standards - Provides native platform and full screen capabilities using HTML5, CSS3, and JavaScript
    GO!
    Download
    Essential Debugging Tools
    Get your app to the stores faster.
    Debug
    Intel® XDK helps decrease your testing and debugging
    time and get your app to market faster.
    Testing

    • Preview your app while editing in a separate browser window or on your device with Live Preview
    • Use the App Preview app for iOS*, Android*, Windows* 8, and Windows* Phone 8 for full testing on your device
    Emulator

    • Simulate your app running on different phone and tablet skins before deployment
    • Quickly switch to debugger to debug your app inside the device emulator
    JS Remote Debugger and Profiler for Android

    • Efficiently debug apps remotely with JS Remote Debugger for Android
    • View memory, frames, and events profiling results to get the best performance out of your app
    More app reliability.
    Tune App Performance
    App Dev User
    Remote JS Performance
    Profiler for Android
    • Quickly pinpoints app performance bottlenecks
    • Round-trip capable, modify within the app
    Xlint Platform-Compatibility CSS Checker
    • Xlint* is a Brackets* HTML5 editor extension
    • Reports cross-platform CSS3 compatibility issues
    • Tests against W3C specs for animations, color level, shadings
    Work Efficiently / Stay On Schedule
    App Dev User
    App Preview on-device Testing
    • Enables on-device testing of hybrid apps, without going through app store submission process
    Live Development
    Side-by-side testing
    • Enables faster testing and editing with real-time side-by-side app preview
    • Allows developers to view changes rendered simultaneously while editing
    GO!
    Download
    Easier Build, Faster Deployment
    Building your application for every platform
    has never been this fast and easy.
    Deploy
    Build cross-platform apps easily for many app stores and web platforms.

    • Select your target store and build! Your app is ready for deployment
    • Hybrid or web apps for Apple* App Store, Google* Play, Windows* 8 and Windows* 8 Phone Stores. Also, Amazon*, Tizen*, Facebook*, Chrome* Stores.
    • For Android* devices, build with Crosswalk*, an open source web-runtime to greatly improve your media and games apps with high-performance WebGL* and WebAudio* support
    Create apps for every need and every device.
    Easier Build
    App Dev User
    Build Hybrid and Web Apps
    • Write Hybrid or Web apps once, and deploy to many app stores
    Faster Deployment
    App Dev User
    Reach More App Stores
    • Apple* App Store
    • Google* Play
    • Nook* Store
    • Amazon Store
    • Windows Store
    • Tizen Store
    • Facebook
    • Chrome

    C++11 Features Supported by Intel® C++ Compiler

    $
    0
    0


    Starting in 11.0 the Intel(R) C++ Compiler has supported some of the C++11 features (previously called C++0x). With the latest release of Intel C++ Composer XE for Windows*, Linux* and Mac OS* X 2013 SP1, more C++11 features are supported.

    Standard#Core Language FeaturesVersion 11.1Version 12.0Version 12.0 Update 6 or 12.1Version 13.0Version 14.0
    N1610Initialization of class objects by rvaluesYesYesYesYesYes
    N1720static_assertYesYesYesYesYes
    N1737Multi-declarator auto-YesYesYesYes
    N1757Right angle bracketsYesYesYesYesYes
    N1791Extended friend declarationsPartialYesYesYesYes
    N1984auto: Deducing the type of variable from its initializer expression-YesYesYesYes
    N1986Delegating constructors----Yes
    N1987Extern templatesYesYesYesYesYes
    N2118Rvalues references-YesYesYesYes
    N2170Universal character names in literals--YesYesYes
    N2235Generalized constant expressions---PartialYes
    N2242variadic templates v0.9--YesYesYes
    N2249char16_t/char32_t types--Partial on Windows;
    Yes on Linux & Mac OS X
    Partial on Windows;
    Yes on Linux & Mac OS X
    Yes
    N2253Extended sizeof-----
    N2258alias templates--YesYesYes
    N2341Alignment: Adding Alignment Support to the C++ Programming Language-----
    N2342Standard-layout and trivial types-----
    N2343decltype v1.0-YesYesYesYes
    N2346deleted and defaulted functions-YesYesYesYes
    N2347Explicit enum bases and scoped enums---YesYes
    N2347Strongly typed enumsPartialPartialPartialPartialYes
    N2431nullptr--YesYesYes
    N2437Explicit conversion operators---YesYes
    N2439Rvalue references for *this----Yes
    N2442Raw string literals----

    Yes

    N2535Inline namespaces----Yes
    N2540Inheriting constructors-----
    N2541auto: Trailing return types-YesYesYesYes
    N2541Late-specified return types--YesYesYes
    N2544Unrestricted unions----Yes on Linux & OS X
    N2546auto v1.0: Removal of auto as a storage-class specifier-YesYesYesYes
    N2550Lambdas v0.9: Lambda Expressions and Closures-YesYesYesYes
    N2555variadic templates v1.0--YesYesYes
    N2634New-style Expression SFINAE (N2634)--YesYesYes
    N2657Local and unnamed types as template arguments-YesYesYesYes
    N2658Lambdas v1.0: Constness of Lambda Functions-YesYesYesYes
    N2670Minimal support for garbage collection-----
    N2672General initializer lists---PartialYes
    N2756Non-static data member initializers----Yes
    N2761Standard attributes (N2761)--YesYesYes
    N2764Forward declared enumsPartialPartialPartialPartialYes
    N2765User-defined literals-----
    N2844Rvalue references v2-YesYesYesYes
    N2927Lambdas v1.1: New wording for C++0x Lambdas-YesYesYesYes
    N2928Explicit Virtual Overrides----Yes
    N2930Range-based for loops---YesYes
    N2947Additional type traits---YesYes
    N3050noexcept or Allowing move constructors to throw----Yes
    N3052Conversions of lambdas to function pointers---YesYes
    N3053RValues: Defining Move Special Member Functions----Yes
    N3206Explicit virtual overrides -> Override control: Eliminating Attributes-----
    N3272override and final----Yes
    N3276decltype v1.1: Decltype and Call Expressions-YesYesYesYes
    Core issue 382Allow typename outside of templates-YesYesYesYes
    DR226Default template arguments for function templates--YesYesYes
     Core Language Features: Concurrency     
    N2179exception_ptr-YesYesYesYes
    N2239Reworded sequence points-----
    N2440quick_exit-----
    N2427atomic types and operations---YesYes
    N2429Memory model-----
    N2547Atomics in signal handlers-----
    N2659Thread-local storage-----
    N2660Magic staticsYes on Linux & OS XYes on Linux & OS XYes on Linux & OS XYes on Linux & OS XYes on Linux & OS X
    N2664Data-dependency ordering-----
    N2748Strong compare and exchange-----
    N2752Bidirectional fences-----
    N2782Data-dependency ordering: function annotation-----
     Core Language Features: C99     
    N1653C99 preprocessorYesYesYesYesYes
    N1811long longYesYesYesYesYes
    N2340__func__YesYesYesYesYes
    N1988Extended integer types-----


    On Windows environment when using Intel C++ compiler with Visual Studio 2010* or 2012*, the C++11 features supported by Visual C++ 2010/2012 are enabled by default. Use "/Qstd=c++11" to turn on the support for all other cases.
    On Linux or Mac OS X environment use "-std=c++11".

    Note: /Qstd=c++0x (-std=c++0x on Linux or Mac OS X) is still supported. it is the same as /Qstd=c++11(-std=c++11 on Linux or Mac OS X).
    Please read the documentation for detail information under /Qstd (-std on Linux* or Mac OS* X) option.

    Other related articles

    1. C++14 Features Supported by Intel® C++ Compiler
    2. C++11 FAQ by Bjarne Stroustrup
    3. C99 Support in Intel C++ Compiler article for supported C99 features.

     

  • C++11
  • C++0x
  • Learning Lab
  • VersionSpecific
  • Sviluppatori
  • Apple OS X*
  • Linux*
  • Microsoft Windows* (XP, Vista, 7)
  • C/C++
  • Intermedio
  • Compilatore C++ Intel®
  • Intel® C++ Composer XE
  • Intel® Composer XE
  • Intel® Parallel Composer
  • URL
  • Learning Lab
  • C-Compiler-Learn
  • Data transfer of an “array of pointers” using the Intel® Language Extensions for Offload (LEO) for the Intel® Xeon Phi™ coprocessor

    $
    0
    0

    The Intel® Parallel Studio XE 2015 Composer Editions for C++ Windows* and Linux* have a feature enhancement supporting data transfer of an “array of pointers” with the Intel® Language Extensions for Offload (LEO) for the Intel® Xeon Phi™ coprocessor.

    The feature adds support under the LEO offload data marshalling model for transferring a pointer type that is an “array of pointers”, where the element-type of the variable reference (variable-ref) used in the data transfer clauses (i.e in, out, inout, nocopy) of the #pragma offload/offload_transfer is a pointer to a standard data type (i.e. signed char, unsigned char, signed int, unsigned int, float, double) or bit-wise copyable type.

    Under the offload data marshalling model, each data movement clause (in, out, inout, nocopy) shares a common basic syntax shown in the details below. The feature enhancement includes new modifiers for specifying details related to the array of pointers as discussed below.

    Syntax:   
                    #pragma offloadclause [ clause …]
                    #pragma offload_transferclause [ clause …]

                    Where clause may include the data transfer clauses of:

                                  in ( variable-ref [, variable-ref …] [ modifier [ modifier … ] ])
                                  out ( variable-ref [, variable-ref …] [ modifier [ modifier … ] ])
                                  inout (variable-ref [, variable-ref …] [ modifier [ modifier … ] ])
                                  nocopy (variable-ref [, variable-ref …] [ modifier [ modifier … ] ])

                    And, specific to using with an array of pointers, the modifier may be:

                                  length ( element-count-expr)
                                  extent (start :length )
                                  alloc_if (condition )
                                  free_if (condition )
                                  align (align-expr)
                                  alloc (identifier [ c-shape])
                                  alloc ([c-shape])
                                  alloc_extent (start :length )
                                  into (variable-ref)
                                  into_extent (start :length )

    For the array of pointers, the variable-ref specifies the pointers in the pointer array whose pointed-to data is to be transferred. The elements of each pointer that are to be transferred may be specified with either a length modifier or an extent modifier. When a length modifier that is a scalar integral expression is used, then that many elements pointed to by each pointer in the array are transferred, beginning with the 0th element. A length modifier that is an array expression specifies a set of length values that apply one-to-one with the pointers in the variable-ref. The first length value applies to the first pointer, the second length to the second pointer and so on. The starting element to transfer is 0 in each case.

    Example:

              //  Transfer the dark-green elements in the pointer arrays
              //  See figure 1 below
    
              int *p[4];          // assume pointers are assigned values
              ...
              #pragma offload …in( p[0:4] : length(2) )
              ...

    The alternative to using the length modifier is to use the extent modifier. This modifier allows two array expressions to be written. The first is an array of starting element values. The second is an array of length values. The one-to-one correspondence between pointer elements and start and length values is the same as that of the length modifier.

    Example:

              //   Transfer the dark-green elements in the pointer arrays
              //   See figure 2 below
    
              int start[4] = {0,1,0,2};
              int len[4] =   {1,1,3,3};
              int *p[4];    // assume pointers are assigned values
              …
              #pragma offload …in( p[0:4] : extent( start[0:4] : len[0:4] ) )
              …

    The alloc_if, free_if, and align modifiers when used with a single pointer are scalar expressions. When used with an array of pointers these modifiers may take an array expression and follow the same rule of one-to-one correspondence as the length and extent modifiers discussed earlier.

    The alloc and into modifiers when used with a single pointer are scalar expressions.  When used with an array of pointers these modifiers may take an array expression and follows the same rule of one-to-one correspondence as the length and extent modifiers discussed earlier. The alternative is to use alloc_extent and into_extent. Similar to the extent modifier, when used with an array of pointers they take two array expressions separated by a colon. The first array expression is a set of start values. The second array expression specifies a set of element counts.

    NOTE: For each of the modifiers discussed above, when an array expression is allowed, a scalar expression may be specified. Then, that expression value is expanded to the size of the pointer array.

    When a variable-list is used in an in/out/inout/nocopy clause and the list contains variables of pointer types, all pointer variables must be either plain pointers or arrays of pointers. Then, the modifiers used, such as length or extent can be consistent with all the pointer variables in the list.

    Refer to the Intel® Parallel Studio XE 2015 Composer Edition for C++ product documentation for additional details.

  • Sviluppatori
  • Linux*
  • Microsoft Windows* (XP, Vista, 7)
  • Microsoft Windows* 8
  • C/C++
  • Intermedio
  • Compilatore C++ Intel®
  • Intel® C++ Composer XE
  • Intel® Composer XE
  • Intel® Parallel Composer
  • Strumenti di sviluppo
  • Architettura Intel® Many Integrated Core
  • Server
  • URL
  • Area tema: 

    IDZone

    Using the Fortran 2008 BLOCK construct with the Intel® Xeon Phi™ coprocessor

    $
    0
    0

    The Intel® Parallel Studio XE 2015 Composer Editions for Fortran Windows* and Linux* have a feature enhancement supporting the Fortran 2008 standard BLOCK construct.

    This feature support includes use with the Intel® Xeon Phi™ coprocessor where the use is within code that executes exclusively on the coprocessor but excluding inside a structured block of an OpenMP* directive. It is a general usage restriction applicable on the host and coprocessor that a BLOCK construct cannot appear inside a structured block of an OpenMP* directive and such attempted use evokes a compile-time error.

    For the Intel® Xeon Phi™ coprocessor and use with offloaded code, this feature only supports use of a BLOCK construct within a the target of an offload execution, meaning inside an offloaded subprogram.

    A BLOCK construct cannot appear inside a structured block of a !DIR$ OFFLOAD OMP directive or !DIR$ OFFLOAD BEGIN / END OFFLOAD directives. Use with the former (OMP specific) directive evokes a compile-time error. Use with the latter directive pair does not evoke any compile-time diagnostics; however, the use should not be considered safe and program behavior involving such use is unpredictable.

    The use of a BLOCK construct with offloading should be restricted to within the target of an offload execution (i.e inside an offloaded subprogram).

    For example:

              subroutine adj_temp
              !dir$ attributes offload : mic :: calc_temp…
              !  Offload call of calc_temp
              !dir$ offload begin target (mic:0)
                     call calc_temp
               …
               end subroutine adj_temp
    
               !dir$ attributes offload : mic :: calc_temp
               subroutine calc_temp
               …
    
               !  Use within an offloaded subprogram but outside a
               !  structured block of an OpenMP* directive is supported
               block
                       integer :: iTemp
                       iTemp=20
                       print "(A,I2)",”In block, iTemp=',iTemp
               end block…
               end subroutine calc_temp

    Code compiled to execute natively (/Qmic [-mmic]) on the Intel® Xeon Phi™ coprocessor can use a BLOCK construct under the same usage requirement as the host CPU, that is, a BLOCK construct cannot appear inside a structured block of an OpenMP* directive.

    This feature enhancement is available in the Fortran Intel® 15.0 compiler.

    Refer to the Intel® Parallel Studio XE 2015 Composer Edition for Fortran product documentation for additional details.

  • Sviluppatori
  • Linux*
  • Microsoft Windows* (XP, Vista, 7)
  • Microsoft Windows* 8
  • Fortran
  • Intermedio
  • Intel® Composer XE
  • Compilatore Fortran Intel®
  • Intel® Fortran Composer XE
  • Intel® Parallel Composer
  • Intel® Visual Fortran Composer XE
  • Strumenti di sviluppo
  • Architettura Intel® Many Integrated Core
  • Server
  • URL
  • Area tema: 

    IDZone

    Data transfer of non-contiguous array elements using the Intel® Language Extensions for Offload (LEO) for the Intel® Xeon Phi™ coprocessor

    $
    0
    0

    The Intel® Parallel Studio XE 2015 Composer Editions for C++ Windows* and Linux* have a feature enhancement supporting data transfer for non-contiguous array elements with the Intel® Language Extensions for Offload (LEO) for the Intel® Xeon Phi™ coprocessor.

    The feature adds support under the LEO offload data marshalling model for transferring non-contiguous array elements within an array variable reference (variable-ref) in the data transfer clauses (i.e. in, out, inout, nocopy) of the #pragma offload/offload_transfer statement.

    Under the offload data marshalling model, each data transfer clause (in, out, inout, nocopy) shares a common basic syntax shown in the details below. The feature enhancement enables specifying a value for stride in the c-shape specification described below.

    Syntax:
                #pragma offloadclause [ clause …]
                #pragma offload_transferclause [ clause …]

                Where clause may include the data transfer clauses of:

                            in (variable-ref [, variable-ref …] [ modifier [ modifier … ] ])
                            out (variable-ref [, variable-ref …] [ modifier [ modifier … ] ])
                            inout (variable-ref [, variable-ref …] [ modifier [ modifier … ] ])
                            nocopy (variable-ref [, variable-ref …] [ modifier [ modifier … ] ])

                 And variable-ref is:

                             identifier
                             variable-ref , identifier
                                         Use the following syntax for variable-ref
                                              •    variable-name: length ( number-of-elements)
                             variable-ref[c-shape]
                                         Use the following syntax for variable-ref
                                              •    variable-name [ start :number-of-elements ]   denotes contiguous
                                                   set of array elements
                                              •    variable-name[start :  number-of-elements:stride]   denotes either
                                                    contiguous or non-contiguous set of array elements
                 And modifier is:

                              Unchanged by the feature enhancement. Refer to the User and Reference Guide
                              for the Intel® C++ Compiler 15.0
    for details.

    The following example illustrates the use of the feature enhancement with non-unit stride with various data movement clauses and modifiers.

    --------------------------------------------------------------------------

    Example:
    #include <stdio.h>#define ALLOC    alloc_if(1)#define No_ALLOC alloc_if(0)#define FREE     free_if(1)#define No_FREE  free_if(0)#define REUSE    alloc_if(0) free_if(0)__declspec( target (mic)) int *a, *b, *c, *d;__declspec( target (mic)) int n=16;__declspec( target (mic))void print_array(char *str,int * array,int start,int count){   printf(str);   printf(" %d",array[start:count]);   printf("\n");   fflush(0);}void print_header(char *str){   int i;   printf(str);   for (i=1;i < strlen(str); i++)       printf("=");   printf("\n");   fflush(0);}void initialize(){   int i;   for (i = 0; i < n; i++)      a[i]=i+2;   b[0:n]=1;   c[0:n]=a[0:n];   d[0:2*n]=0;}void IN_with_stride(){   int i;   char msg[20]="";   print_header("Illustrate IN with non-unit stride\n");   print_array("host : a =",a,0,n);   // Allocate space for a only, allocate/transfer b   #pragma offload_transfer target(mic:0) mandatory \                                 nocopy(a : length(n) ALLOC No_FREE) \                                 in(b : length(n) ALLOC No_FREE)   // Transfer 1/2 of the values of array a with non-unit stride   #pragma offload target(mic:0) mandatory \                                 in(a[0:n/2:2] : REUSE ) \                                 nocopy(b : REUSE)   {      sprintf(msg,"-> mic%d : b (before) =",_Offload_get_device_number());      print_array(msg,b,0,n);      for (i = 0; i < n; i++)          b[i] = a[i];      sprintf(msg,"-> mic%d : a =",_Offload_get_device_number());      print_array(msg,a,0,n);      sprintf(msg,"-> mic%d : b (after) =",_Offload_get_device_number());      print_array(msg,b,0,n);   }   // Free allocations   #pragma offload_transfer target(mic:0) mandatory \                                  nocopy(a,b : No_ALLOC FREE)   printf("\n");}void IN_with_ALLOC_with_stride(){   int i,l,cnt,s;   char msg[20]="";   print_header("Illustrate IN with ALLOC with non-unit stride\n");   print_array("host : c =",c,0,n);   l = 0;   cnt = n/2;   s = 2;   // Allocate partial array and transfer non-unit stride elements   // Ensure the number of elements transferred plus the stride   // does not exceed the size of the partial allocation   #pragma offload target(mic:0) mandatory \                   in(c[l:(cnt/s)+(s%2):s] : alloc (c[l:cnt]) ALLOC FREE)   {      sprintf(msg,"-> mic%d : c =",_Offload_get_device_number());      print_array(msg,c,l,cnt);   }   printf("\n");}void INTO_with_stride(){   int i,l,cnt,s;   char msg[20]="";   print_header("Illustrate INTO with non-unit stride\n");   c[0:n]=a[0:n];   print_array("host : a =",a,0,n);   print_array("host : c (before) =",c,0,n);   print_array("host : d[0:n] =",d,0,n);   print_array("host : d[n:n] =",d,n,n);   l = n/2;   cnt = n/2;   s = 2;   // Allocate d only   #pragma offload_transfer target(mic:0) mandatory \                                   nocopy(d : length(2*n) ALLOC No_FREE)   // Transfer a elements with non-unit stride into d on coprocessor only   #pragma offload target(mic:0) mandatory \                                 in(a[0:cnt:s] : into (d[n:cnt:s]) REUSE)   {      sprintf(msg,"-> mic%d : d[0:n] =",_Offload_get_device_number());      print_array(msg,d,0,n);      sprintf(msg,"-> mic%d : d[n:n] =",_Offload_get_device_number());      print_array(msg,d,n,n);   }   // Transfer d elements with non-unit stride into c on host only   // Free the allocation   #pragma offload_transfer target(mic:0) mandatory \                            out(d[n:cnt:s] : into (c[1:cnt:s]) No_ALLOC FREE)   print_array("host : c (after) =",c,0,n);   printf("\n");}int main(int argc, char* argv[]){   a = (int *) _mm_malloc(n*sizeof(int), 64);   b = (int *) _mm_malloc(n*sizeof(int), 64);   c = (int *) _mm_malloc(n*sizeof(int), 64);   d = (int *) _mm_malloc((2*n)*sizeof(int), 64);   initialize();   IN_with_stride();   IN_with_ALLOC_with_stride();   INTO_with_stride();}

     

  • Sviluppatori
  • Linux*
  • Microsoft Windows* (XP, Vista, 7)
  • Microsoft Windows* 8
  • C/C++
  • Intermedio
  • Compilatore C++ Intel®
  • Intel® C++ Composer XE
  • Intel® Composer XE
  • Intel® Parallel Composer
  • Strumenti di sviluppo
  • Architettura Intel® Many Integrated Core
  • Server
  • URL
  • Area tema: 

    IDZone

    Using Intel® MPI Library 5.0 with MPICH based applications

    $
    0
    0

    Why it is needed?

    Different MPI implementations have their specific benefits and advantages. So in the specific cluster environment the HPC application with the other MPI implementation can probably perform better.

     Intel® MPI Library has the following benefits:

    • Support of the wide range of cluster hardware and software
      • Full support and tuned performance of all modern Intel processors
      • Full support and tuned performance of wide variety of modern interconnects, full support of Intel interconnects
    • Integration with Intel® Trace Analyzer and Collector
      • Tracing all MPI events in parallel application;
      • Disbalance detection;
      • MPI correctness checks;
      • API for user code instrumentation;
    • Extended debug and statistics output
      • Intel MPI Library has an ability to output key statistics about parallel run to identify issues and tune performance;
    • Full control of parallel application execution
      • Rich set of controls via environment variables, control flags or configuration files
    • Support

     

    Requirements

    To use Intel MPI Library the following is required:

    • System based on the Intel® 64 or Intel® MIC architecture;

    How to

    Note. There are two possible ways  to use Intel MPI Library 5.0 for MPICH based applications:

    In this article the usage of ABI compatibility will be covered.

    The MPI-3 standard has announced a new routine MPI_Get_library_version to determine what MPI implementation is used in runtime.
    This small MPI application demonstrates its functionality.

    $ cat ./version_info.c
    #include "mpi.h"
    #include <stdio.h>
    
    int main (int argc, char *argv[])
    {
        int rank, namelen;
        char mpi_name[MPI_MAX_LIBRARY_VERSION_STRING];
    
        MPI_Init (&argc, &argv);
    
        MPI_Comm_rank (MPI_COMM_WORLD, &rank);
    
        MPI_Get_library_version (mpi_name, &namelen);
    
        if (rank == 0)
            printf ("Hello world: MPI implementation:\n %s\n", mpi_name);
    
        MPI_Finalize ();
    
        return (0);
    }
    

     

    1. For testing purposes compile the application with MPICH
       
      $ export PATH=~/mpich/3.1.2/bin/:$PATH
      $ mpicc ./version_info.c -o version_info
    2. Check that MPI library is linked dynamically (in other case recompilation from sources is needed)
       
      $ ldd ./version_info | grep libmpi
       libmpi.so.12 => /home/user/mpich/3.1.2/lib/libmpi.so.12 (0x00007f44e7c29000)
    3. For MPICH-3 the MPI application shows
       
      $ mpiexec -n 2 ./version_info
      Hello world: MPI implementation:
       MPICH Version: 3.1.2
      MPICH Release date: Mon Jul 21 16:00:21 CDT 2014
      MPICH Device: ch3:nemesis
      MPICH configure: --prefix=/home/user/mpich/3.1.2/
      MPICH CC: gcc    -O2
      MPICH CXX: g++   -O2
      MPICH F77: gfortran   -O2
      MPICH FC: gfortran   -O2
      
    4. Make Intel(R) MPI Library loaded
       
      $ export LD_LIBRARY_PATH=/opt/intel/impi/5.0.1.035/intel64/lib/:$LD_LIBRARY_PATH
      $ mpiexec -n 2 ./version_info
      Hello world: MPI implementation:
       Intel(R) MPI Library 5.0 Update 1 for Linux* OS
    5. On step 4. only the  library was changed, the rest of MPI implementation was MPICH. It is simple to change it also
       
      $ source /opt/intel/impi/5.0.1.035/intel64/bin/mpivars.sh
      $ mpiexec.hydra -V
      Intel(R) MPI Library for Linux* OS, Version 5.0 Update 1 Build 20140709
      Copyright (C) 2003-2014, Intel Corporation. All rights reserved.
      $ mpiexec.hydra -n 2 ./version_info
      Hello world: MPI implementation:
       Intel(R) MPI Library 5.0 Update 1 for Linux* OS
      

    Conclusion

    For evaluation of this ABI compatibility feature of Intel MPI Library one can download the Free 30-Day Evaluation Version or use Intel MPI Library Runtime Environment free of charge (with limited support options). For more details please refer to the Intel MPI Library Licensing FAQ.

     

  • Sviluppatori
  • Partner
  • Professori
  • Studenti
  • Linux*
  • Server
  • Avanzato
  • Principiante
  • Intermedio
  • Intel® Cluster Toolkit
  • Intel® Trace Analyzer and Collector
  • Intel® MPI Library
  • Intel® Cluster Studio
  • Intel® Cluster Studio XE
  • Intel® Cluster Ready
  • Message Passing Interface
  • Elaborazione basata su cluster
  • Strumenti di sviluppo
  • Server
  • URL
  • Per iniziare
  • Miglioramento delle prestazioni
  • Librerie
  • Area tema: 

    IDZone

    Intel® C++ Compiler 15.0 for Linux Sets “-ansi-alias” by Default, Noncompliant Code May Fail

    $
    0
    0

    Beginning with version 15.0, the Intel® C++ Compiler for Linux enables -ansi-alias by default at optimization level 2 (-O2). The -ansi-alias option indicates that the code complies with ANSI aliasing rules.

    If the application code adheres to ANSI aliasing rules, this change allows the compiler to make aggressive optimizations. The effect of this change on runtime performance depends on the application, the optimization methods supported by the compiler, and the compiler switches used.

    If the application code does not follow ANSI aliasing rules, then this option may cause compile time or runtime failures. 

    Use the –fno-ansi-alias option to disable this behavior. Note that -fstrict-aliasing has the same behavior as -ansi-alias, and -fno-strict-aliasing will negate both options as well. For more information, please refer to the User and Reference Guide for the Intel® C++ Compiler 15.0.

  • Sviluppatori
  • Linux*
  • C/C++
  • Intermedio
  • Compilatore C++ Intel®
  • Architettura Intel® Many Integrated Core
  • Ottimizzazione
  • Vettorizzazione
  • URL
  • Argomenti sui compilatori
  • Area tema: 

    IDZone

    What’s New in the Intel Compiler

    $
    0
    0

    The list below summarizes new features in the Intel® C++ Compiler 15.0 and the Intel® Fortran Compiler 15.0. For more details about changes in the Intel compilers since the previous release, including a list of new options, please refer to the ‘What’s New’ section in the release notes (C++, Fortran).

    Feature Highlights
    •    Redesign of  the optimization reports (including vec-report, loop optimizations, and inlining reports)
    •    OpenMP 4.0 support in Intel Compiler 15.0
    •    New features targeting Intel® Xeon Phi™ coprocessors
    •    Microsoft vectorcall calling convention supported

    Intel® C++ Compiler 15.0
    •    Intel® C++ Compiler 15.0 for Linux Sets “-ansi-alias” by Default
    •    Full C++11 Support (Prerequisite: Dependent headers and libraries also require full language support.)
    •    Aligned “new” support via a new header file “aligned_new” on Linux* and Windows*
    •    What’s new in the Intel C++ Compiler integration with Microsoft* Visual Studio*

    Intel® Fortran Compiler 15.0
    •    Full language Fortran 2003 support
    •    BLOCK from Fortran 2008
    •    OpenMP* 4.0 WORKSHARE

     

  • Sviluppatori
  • Linux*
  • Microsoft Windows* (XP, Vista, 7)
  • Microsoft Windows* 8
  • C/C++
  • Fortran
  • Avanzato
  • Principiante
  • Intermedio
  • Compilatore C++ Intel®
  • Compilatore Fortran Intel®
  • OpenMP*
  • Strumenti di sviluppo
  • Processori Intel® Core™
  • Architettura Intel® Many Integrated Core
  • Ottimizzazione
  • Elaborazione parallela
  • Threading
  • Vettorizzazione
  • URL
  • Argomenti sui compilatori
  • Area tema: 

    IDZone

    New Features for Intel® MIC Architecture in the Intel Compiler

    $
    0
    0

    MVarandas Soluções em Tecnologia escolhe Crosswalk como fundação de seus aplicativos HTML5 para Android

    $
    0
    0

    Usado em vários restaurantes como única forma de fazer um pedido, o "Menew Cardápio Digital", software desenvolvido por MVarandas Soluções em Tecnologia, está recebendo várias melhorias graças ao Crosswalk,  HTML5 runtime para Android desenvolvido pela Intel. O bom resultado também é fruto da colaboração entre as equipes de desenvolvimento de ambas as empresas.

    "Menew Cardápio Digital" é um cardápio digital disponível aos clientes em suas mesas, oferecendo uma experiência imersiva e substituindo o antigo cardápio de papel. Rodando em um tablet Android convencional, o aplicativo permite fácil navegação entre as opções do menu, informações detalhadas sobre os pratos oferecidos, com destaque para as deliciosas fotos dos pratos em alta resolução. E mais, você ainda pode fazer seu pedido usando o tablet!

    O aplicativo foi desenvolvido usando HTML5 dentre outras tecnologias web modernas e é suportado em tablets de baixo custo.

    Intel entrou em contato com MVarandas depois que um de seus desenvolvedores se interessou pelo aplicativo e todo seu potencial enquanto fazia uma refeição em um restaurante: "- O aplicativo usa a tecnologia HTML5, encaixa-se perfeitamente com a proposta do projeto de software livre Crosswalk.”

    Estava claro após o primeiro contato com a MVarandas, que um dos principais desafios era performance. O aplicativo era geralmente implantado em tablets antigos ou de baixo custo, com menor poder de processamento e com versões antigas do Android WebView, resultando em um desempenho inadequado em vários casos.

    Crosswalk caiu como uma luva: o fato de Crosswalk ser baseado na última versão do Chromium e atualizado a cada 6 semanas, gerou ganhos em performance e abriu a opção de se usar o que há de mais moderno em tecnologias web. Adicionalmente, MVarandas também pode desfrutar features exclusivas como: screen orientation lock (travar orientação da tela), manifest, JavaScript Single Instruction Multiple Data (SIMD) e muito mais.

    Adicionalmente, MVarandas agora está em total controle do seu ciclo de desenvolvimento, já que cabe a eles definir quando atualizar a versão do Crosswalk usada em seus aplicativos.

    Equipes da Intel e MVarandas uniram forças e reempacotaram o "Menew Cardápio Digital" usando Crosswalk. A performance melhorou quase sem esforço algum e Crosswalk também abriu um leque de opções para MVarandas usar o que há de mais moderno em HTML5, o que não poderia ser feito antes com Android WebView.

    Em pouco tempo, MVarandas já estava confiante em atualizar a versão em produção do aplicativo usando Crosswalk. Até então, um restaurante já migrou completamente para a versão do "Menew Cardápio Digital" baseada no Crosswalk e mais estão à caminho, já que os testes de campo estão se mostrando positivos. Tão positivos que MVarandas está usando Crosswalk também em outros produtos.

    Marcus Varandas Filho (MVarandas Soluções em Tecnologia, Gerente) :
    "Não conhecíamos o Crosswalk e quando fomos apresentado ao projeto ficamos realmente empolgados. Revelou ser a solução de muitos problemas de performance em nosso projeto de "Menew Cardápio Digital" para tablets. A parceria com a Intel, através de varias reuniões e de grande aprendizado, hoje dá frutos além das nossas expectativas. A ferramenta abriu grandes possibilidades e já temos planos para utilizar os recursos do Crosswalk em vários outros projetos.”

    Isaac Marinho (MVarandas Soluções em Tecnologia, Software Engineer) :
    "Meu primeiro contato com o Crosswalk foi instigante e desafiador. Instigante porque me pareceu uma solução para problemas de performance, que enfrentamos ao distribuir nossa aplicação "Menew Cardápio Digital” para dispositivos menos robustos, e desafiador porque até então eu não havia ouvido nada sobre tal projeto. Ao conhecer melhor o projeto e ter a oportunidade de lidar com ele, na solução de uma situação-problema, pude constatar que por sua simplicidade (algumas linhas de comando e seu APK está pronto para distribuir) e sua eficiência, ele não só foi uma solução para problemas pontuais como também ajudou a otimizar o desempenho de nossa aplicação de um modo geral. Estou ansioso para disseminar o conhecimento a respeito do Crosswalk com a nossa equipe de desenvolvimento e poder utilizá-lo nas demais aplicações que temos desenvolvido para dispositivos móveis.”

    Alexis Menard (Intel, Software Engineer) :
    "Quando apresentei o Crosswalk, eu imediatamente percebi que era exatamente o que MVarandas estava procurando. Então nos encontramos várias vezes para adaptar o "Menew Cardápio Digital” ao Crosswalk e até descobrimos oportunidades de melhorias, algo que não seria possível com o Android WebView de 2011. Tem sido ótimo trabalhar com eles e a colaboração foi até além do planejado.”

    Marinaldo Barreto (Restaurante Forno de Pizza - Campina Grande) :
    "O "Menew Cardápio Digital" deu uma nova dinâmica à casa. Em relação ao novo aplicativo baseado no Crosswalk, foi visível a mudança: recebemos elogios dos consumidores a respeito da agilidade do novo aplicativos rodando nos tablets. A equipe de garçons também observou que a mudança foi positiva, pois facilitou e agilizou o trabalho dos mesmos, diminuindo o tempo de serviço e consequentemente, o tempo de espera até o produto chegar à mesa do cliente. Indico o serviço a todos, vem sendo definitivamente uma boa experiência.”

    Sobre MVarandas Soluções em Tecnologia :
    Com mais de 5.000 usuários instalados no Brasil e referência no mercado desde 1984, a MVarandasé uma empresa fornecedora de Tecnologia da Informação especializada no desenvolvimento de sistemas informatizados de gestão e controle de empresas.
    Perfeitamente integrados ao negócio de cada cliente, esses sistemas tem seu desenvolvimento voltado essencialmente aos setores de restaurantes, bares, night clubs, pizzarias, hotéis, motéis, pousadas e afins.

    Menew Cardápio Digital

    Da esquerda para a direita : Marinaldo Barreto, Marcus Varandas Filho and Alexis Menard

     

     

  • Sviluppatori
  • Partner
  • Android*
  • Android*
  • HTML5
  • HTML5
  • Principiante
  • Intermedio
  • Strumenti di sviluppo
  • Open source
  • Telefono
  • Tablet
  • URL
  • Area tema: 

    HTML5
  • Android*
  • 在采用 TouchScript 的 Unity* 3D 中实施手势序列

    $
    0
    0

    Download PDF

    By Lynn Thompson

    当配置触摸目标控制一个场景中的其他元素时,应最大限度地减少控制元素所占的屏幕空间。 这样,您可以将更多超极本™ 设备的可视屏幕区域用于显示视觉活动,更少用于用户交互。 实现它的一种方法是,让触摸目标能够处理多手势组合,从而无需在屏幕上设置更多触摸目标。 比如,使用连续点击图形用户界面 (GUI) widget 来触发炮楼旋转并开火,而非使用专门的 GUI widget 开火并使用另一个 widget 旋转炮楼(或 Unity* 3D 场景中的其他资产)。

    本文将介绍如何配置使用触摸目标的场景来控制第一人称控制器 (FPC)。 首先,为基本的 FPC 位置和旋转配置触摸目标;然后,将其扩大为附加功能。 附件功能可通过现有的 GUI widget 来实现,且不需要增加几何。 生成的场景将展示 Windows* 8 上运行的 Unity 3D 能够处理不同序列中使用的多手势。

    配置 Unity* 3D 场景

    我首先导入一个 FBX 地形资产(包括拔高的地势和树木)来设置场景,该资产是我从 Autodesk 3ds Max* 导入的。 然后,我将 FPC 放到地形中心。

    我将场景主摄像头(FPC 的子对象)的景深设置为 -1。 我创建了一个专用 GUI widget 摄像头,包括一个正射投影,宽为 1,高为 0.5,以及 Don’t Clear (不清除)标记。 然后,我创建了一个 GUIWidget 层,并将其设置为 GUI widget 摄像头的裁剪蒙版。

    接下来,我从专用的正投射摄像头的视角为 FPC 在场景中的操作设置了基本的 GUI widget。 在左侧,我为每根手指设置了一个范围。 左侧的小范围可将 FPC 向左侧移动,左侧的环形范围可将其向前移动,左侧中间的范围可将其向右移动,左侧的索引范围可将 FPC 向后移动。 左拇指范围可让 FPC 跳跃,并以顺时针 30 度的方向发射球形弹。

    在右侧 GUI widget 中,我创建了一个立方体(通过正射投影成为正方形)。 我使用拖拽 (pan) 手势来配置此立方体,并将其绑定到 MouseLook.cs 脚本中。 此 widget 的功能与超极本触摸板的功能相似。

    我将这些 GUI widget 放在主摄像头视图之外,并将它们的层设置为 GUIWidget。 图 1 展示了运行时的场景,其中使用了 GUI widget 发射球形弹并控制 FPC 的位置。


    图 1. 带有地形并发射了球形弹的 FPC 场景

    场景中,球形弹从 FPC 发射出,穿过树木。 为了补救,我需要为每棵树配置一个 mesh 或盒式对撞机。 这种场景的另一个问题是,如果我使用触摸板让 FPC 向下看并按环形手指将 FPC 向前移动时,前行速度将变慢。 为了解决这一问题,我限制了按下“向前移动”按钮时的“向下看”角度。

    多次点触

    基本场景包括 FPC 以指定角度从中心向外投弹。 默认从中心向外发射的角度是当俯视 FPC 时顺时针 30 度。

    我为场景配置了多次点触,其能够在少于指定时间微分内启动,改变球形弹发射的角度,然后发射球形弹。 我可以通过控制左拇指跳跃脚本中的浮点变量配置该行为,使其根据序列中点击数量(number of tap)的增加来快速扩大角度。 这些浮点变量可以控制发射角度,并追踪自上一颗球形弹发射后的时间:

    	private float timeSinceFire = 0.0f;
    	private float firingAngle = 30.0f;

    然后,我在左拇指跳跃脚本中配置了 Update 循环来减少跳跃范围手势少于 1/2 秒间隔时的发射角度。 如果点触间隔大于 1/2 秒,或发射角度已经减少到 0 度,则发射角度将重置为 30 度。 代码如下:

    		timeSinceFire += Time.deltaTime;
    
    			if(timeSinceFire <= 0.5f)
    			{
    				firingAngle += -1.0f;
    
    			}
    			else
    			{
    				firingAngle = 30.0f;
    			}
    
    			timeSinceFire = 0.0f;
    
    			if(firingAngle <= 0)
    			{
    				firingAngle = 30;
    			}
    
    
    			projectileSpawnRotation = Quaternion.AngleAxis(firingAngle,CH.transform.up);

    该代码还可制作扫射效果,连续点击可发射球形弹并同时缩减其发射角度(见图 2)。 该效果允许用户定制或在仿真或游戏中的特定状况下使用。


    图 2.连续点击可旋转已发射球形弹的方向。

    缩放与拖拽

    我在图 1 的右下角配置了方块,其作用相当于键盘上的触摸板。 在方块上进行拖拽操作不会移动方块,而会通过传送 FPS 的 MouseLook 脚本向上、下、左和右旋转情景的主摄像头。 同样,方块接收到的缩放手势(与其他平台上的缩放功能类似)不会缩放方块,只会改变主摄像头的视场 (FOV),支持用户缩放主摄像头当前捕获的画面(参见图 3)。 我将配置一个拖拽手势,该手势可在缩放手势将 FOV 返回默认的 60 度后不久启动。

    我通过设置 Boolean 变量 — 拖拽 — 以及浮点变量来控制上次缩放手势操作至今的时间:

    	private float timeSinceScale;
    	private float timeSincePan;
    	private bool panned;

    我将缩放手势启动时的 timeSinceScale 变量设置为 0.0f,并将拖拽手势启动时的拖拽变量设置为“真”。 场景主摄像头的 FOV 在 Update 循环中按照如下方式在触摸板正方体中添加的脚本中进行调整:

    		timeSinceScale += Time.deltaTime;
    		timeSincePan += Time.deltaTime;
    
    		if(panned && timeSinceScale >= 0.5f && timeSincePan >= 0.5f)
    		{
    			fieldOfView += 5.0f;
    			panned = false;
    		}
    
    		if(panned && timeSinceScale <= 0.5f)
    		{
    			fieldOfView = 60.0f;
    			panned = false;
    		}
    
    		Camera.main.fieldOfView = fieldOfView;

    以下是 onScale 和 onPan 函数。 请注意 timeSincePan 浮点变量,该变量可在触摸板用于摄像头时阻止 FOV 持续增加:

    	private void onPanStateChanged(object sender, GestureStateChangeEventArgs e)
        {
            switch (e.State)
            {
                case Gesture.GestureState.Began:
                case Gesture.GestureState.Changed:
                    var target = sender as PanGesture;
                    Debug.DrawRay(transform.position, target.WorldTransformPlane.normal);
                    Debug.DrawRay(transform.position, target.WorldDeltaPosition.normalized);
    
                    var local = new Vector3(transform.InverseTransformDirection(target.WorldDeltaPosition).x, transform.InverseTransformDirection(target.WorldDeltaPosition).y, 0);
                    targetPan += transform.InverseTransformDirection(transform.TransformDirection(local));
    
                    //if (transform.InverseTransformDirection(transform.parent.TransformDirection(targetPan - startPos)).y < 0) targetPan = startPos;
                    timeSincePan = 0.0f;
    				panned = true;
    				break;
    
            }
    
        }
    
    	private void onScaleStateChanged(object sender, GestureStateChangeEventArgs e)
        {
            switch (e.State)
            {
                case Gesture.GestureState.Began:
                case Gesture.GestureState.Changed:
                    var gesture = (ScaleGesture)sender;
    
                    if (Math.Abs(gesture.LocalDeltaScale) > 0.01 )
                    {
    					fieldOfView *= gesture.LocalDeltaScale;
    
    					if(fieldOfView >= 170){fieldOfView = 170;}
    					if(fieldOfView <= 1){fieldOfView = 1;}
    
    					timeSinceScale = 0.0f;
    
    
                    }
                    break;
            }
        }


    图 3. 场景的主摄像头通过适当的 GUI 触摸板模拟器“放大”远距离的特征

    按下并释放,然后快速翻看

    当左侧的小范围接收到按下并释放的手势,然后在 1/2 秒内使用 Flick Gesture (快速翻看手势)时,以下手势序列将会提高 FPC 的水平速度。

    为了添加该功能,首先,我添加了一个浮点变量来追踪范围接收到 Release Gesture (释放手势)后的时间,并添加了一个 Boolean 变量来追踪范围接收 Flicked Gesture(快速翻看手势)的情况:

    	private float timeSinceRelease;
    	private bool flicked;

    作为场景的初始设置,我在左侧小范围脚本中添加了访问 FPC InputController 的脚本,以允许左侧小范围能够调用将 FPC 移动到左侧的操作。 控制 FPC 横向速度的变量不是位于 InputController,而是位于 FPC 的 CharacterMotor。 允许将左侧小范围的脚本加入 CharacterMotor 的配置如下:

    		CH = GameObject.Find("First Person Controller");
    		CHFPSInputController = (FPSInputController)CH.GetComponent("FPSInputController");
    		CHCharacterMotor = (CharacterMotor)CH.GetComponent ("CharacterMotor");

    脚本的 onFlick 函数仅可将快速翻看的 Boolean 变量设置为 True。

    脚本的 Update 函数(每帧调用一次)可按照如下方式改变 FPC 的横向运动速度:

    		if(flicked && timeSinceRelease <= 0.5f)
    		{
    			CHCharacterMotor.movement.maxSidewaysSpeed += 2.0f;
    			flicked = false;
    		}
    
    		timeSinceRelease += Time.deltaTime;
    	}

    该代码可支持用户通过按下并释放左侧小范围,然后在 1/2 秒内快速翻看左侧小范围来提高 FPC 的横向运动速度。 您可以通过任意方式配置降低横向速度的能力,包括按下并释放左侧索引范围,然后使用 Flick Gesture(快速翻看手势)。 请注意,CHCharacterMotor.movement 方法不仅包括 maxSidewaysSpeed,还包括重力、maxForwardsSpeed、maxBackwardsSpeed 和其他参数。 接收它们并于这些参数一起使用的许多 TouchScript 手势和几何可为开发 Unity 3D 场景的触摸界面提供许多选项和策略。 当为这些类型的应用开发触摸界面时,尝试将众多选项缩减为可提供最有效且最符合人体工程学的用户体验的少数选项。

    手势序列的问题

    我在本文的示例中配置的手势序列大量使用了 Time.deltaTime 函数。 我将该微分与确定某个操作的微分之前和之后的手势结合使用。 我在配置这些示例时遇到的两个主要问题是:时间微分的大小和使用的手势。

    时间微分

    我在本文中使用的时间微分是 1/2 秒。 当我使用 1/10 秒这一更短的时间时,手势序列无法识别。 虽然我感觉点触的速度足以让手势序列识别出,但是预期的场景操作并未出现。 这可能是硬件和软件延迟的结果。 因此,当开发手势序列时,应记住目标硬件平台的性能特征。

    手势

    在配置该示例时,最初我准备加入缩放和拖拽手势,然后加入点触和快速翻看手势。 确保缩放和拖拽手势按照预期使用后,我加入了点触手势,这可以让缩放和拖拽手势停止使用。 虽然我可以在拖拽手势之后配置一个缩放序列,但是这种手势序列不符合用户使用习惯。 最有效的序列应在 widget 中包含另一个几何目标,在缩放和拖拽手势后接收点触和快速翻看手势。

    我在本示例中使用了 1/2 秒的时间微分作为操作使用(或不使用)的断点。 虽然它为用户界面 (UI) 增加了一定的复杂性,您可以配置该示例使用多个时间微分。 使用按下并释放手势,然后在 1/2 秒内使用快速翻看手势可以导致水平速度增加;使用按下并释放手势,然后再 1/2 秒至 1 秒之间使用快速翻看手势可以降低水平速度。 以这种方式使用时间微分不仅能够为 UI 提供灵活性,还可用于在场景内部安置“复活节彩蛋”。

    结论

    我为本文配置的手势序列场景在运行 Windows 8 的超极本设备上使用了采用 TouchScript 的 Unity 3D。 实施的序列旨在减少用户与应用交互所需的触目屏幕面积。 用于用户交互的屏幕界面的面积越少,能够用于视觉内容的面积越多。

    当我无法获得一个手势序列按照预期的方式执行时,我能够构建一个可行的替代方案。 此性能调优的一部分是调整 Time.deltaTime 微分,从而获取一个手势序列按照预期在可用的硬件上执行。 同样地,我在本文中构建的 Unity 3D 场景显示,在超极本设备上运行的 Windows 8 能够用于开发使用手势序列的应用。

    相关内容

    关于作者

    Lynn Thompson 是一位 IT 专业人员,在商业和工业计算环境领域拥有二十多年的经验。 最初,他曾在一家电力公司的控制系统更新项目中,使用 CAD 修改并创建控制系统图。 在此期间,Lynn 获得了内布拉斯加大学林肯校区(University of Nebraska, Lincoln)电气工程专业的理学士学位。 在互联网繁荣时期,他继续在一家 IT 整合企业担任系统管理员。 这份工作主要处理多种平台上的操作系统、数据库和应用管理。 在互联网泡沫破灭之后,他为服装、石油和天然气以及国防领域的企业的多种项目提供 IT 咨询服务。 现在,Lynn 又回到原点,担任电力公司的工程师。 后来,Lynn 获得内布拉斯加大学林肯校区 (University of Nebraska, Lincoln) 工程管理专业的工程硕士学位。

     

    英特尔、Intel 标识、超极本和 VTune 是英特尔公司在美国和其他国家的商标。
    *其他的名称和品牌是其他所有者的资产。
    版权所有© 2014 年英特尔公司。 所有权保留。

  • Sviluppatori
  • Microsoft Windows* 8
  • Windows*
  • Unity
  • Intermedio
  • Computing percettivo
  • Sviluppo giochi
  • Interfacce touchscreen
  • Laptop
  • Tablet
  • URL
  • Area tema: 

    IDZone
    Viewing all 664 articles
    Browse latest View live


    <script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>