Главная » Просмотр файлов » Programming Java 2 Micro Edition for Symbian OS 2004

Programming Java 2 Micro Edition for Symbian OS 2004 (779882), страница 67

Файл №779882 Programming Java 2 Micro Edition for Symbian OS 2004 (Symbian Books) 67 страницаProgramming Java 2 Micro Edition for Symbian OS 2004 (779882) страница 672018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 67)

They are allimplemented as Singletons.• OutputTextBox: displays status text• LoadDeleteList: loads a game from the RMS and deletes gamesfrom the RMS• SaveGameForm: saves the current game to the RMS• SetupForm: sets parameters, such as reporting intervals• Cursor: simply stores the location of the cursor for editing cells; theMIDlet goes into edit mode when a game is stopped or paused.When testing different ideas, our standard benchmark is the time taken togenerate the first 150 generations starting with the r Pentomino.7.14.1 Optimizing the LifeCanvas ClassWe start our case study by repeating a lesson: optimization is platformdependent.

The main responsibility of the LifeCanvas class is to renderthe game to the screen when a new generation has been constructed.The design goal is to ensure fast rendering at all zooms, with renderingindependent of screen size (though accepting that rendering could slowdown with the number of live cells to be displayed), fast pan and zoom,and fast redraw after editing.An unsuitable approach is to go through each cell on the screen, checkif it is empty or alive, and paint it in accordingly.

However, out of interestI recently tried this approach to see how bad it would be. On the WirelessToolkit using the default color phone emulator it took 109 s to calculatethe first 150 generations of the r Pentonimo evolution. This compares toabout 48 s using our default rendering.Version 1LifeTime was originally developed on the Nokia 9210 using an earlyimplementation of the Wireless Toolkit. Rendering was clearly a bottleneck. As a consequence a great deal of effort went into ensuring thatpaintCanvas() only updated what had changed; so, for instance, if acell was alive in both the old generation and the new generation, thatlocation was not updated.LIFETIME CASE STUDY371Each call to the painting method carries out the following steps:1.

Fill the whole screen with the background color if we need to repaintthe whole screen (e.g. after displaying a dialog or when just started),or if there is no grid (that is, if the zoom is 0 or 1).2. Paint in the grid lines if we need to repaint the whole screen and thezoom is 2 or 3.3. Work out the offset of the screen in relation to our origin (the visiblearea can be panned around the virtual game field).4. If we did not fill the whole screen with the background color in step1, then enumerate through the old GenerationMap: for each cell, if itis in the visible area and it does not exist in the new GenerationMap,paint it out with the background color (in fact, because painting wassuch a bottleneck, it was slightly faster to paint in a prepared imageof the empty cell using Graphics.drawImage()).5.

Enumerate through the new GenerationMap; for each cell, if it is inthe visible area and it did not exist in the old GenerationMap, paintin the live cell image.6. The cursor may have moved between generations, so paint out thecursor at the old position and paint it in at the new position. Thecursor cell is green if there is a live cell at that location and red if thecell is empty.Version 2However, on the newer Wireless Toolkit emulator (WTK 2.1) and onSymbian OS phones running the CLDC HI VM, a more straightforwardimplementation of paint() ran just as fast on small screens, and onlyslightly slower on larger screens.On each call to our painting method, it carries out the following steps:1.

Fill the whole screen with the background color.2. Paint in the grid lines if the zoom is 2 or 3.3. Work out the offset of the screen in relation to the origin (the visiblearea can be panned around the virtual game field).4. Enumerate through the new GenerationMap; for each cell, if it isin the visible area, call Graphics.fillRect() to paint in thelive cell.5. The cursor may have moved between generations, so paint out thecursor at the old position and paint it in at the new position. Thecursor cell is green if there is a live cell at that location and red if thecell is empty.372WRITING OPTIMIZED CODE7.14.2 Optimizing the LifeEngine ClassLifeEngine contains the algorithm that creates the new generationfrom the old generation. Rather than go through the code line by line, itis probably less painful to give a description.The initial implementation used two GenerationMaps: one to hold thenew generation (thisGeneration), and one to hold the old generation(lastGeneration).• looking at the Game of Life rules, we have to examine each live cell;if it has two or three neighbors it lives, so we create a new cell inthisGeneration at the old cell location• we also have to examine empty cells that have three neighbors.

Theway the program does this is to examine every cell adjacent to everylive cell; if it is empty and has three live neighbors, we create a newcell in thisGeneration at the empty location• having calculated and displayed the new generation, the new generation becomes the old generation and the new generation mapis cleared• run() loops once per generation; it goes through all the cells inlastGeneration and calls createNewCell() to check whetherthe cell should live or die and to check if the eight neighboring cells should live or die; this translates to a lot of calls toisAlive()!One significant optimization was applied.

testedCells is a GenerationMap used to hold the tested cells. So, whenever a cell is checked,whether it is empty or not, a cell with the same position is createdin testedCells. So before testing if a cell should live or die, createNewCell() first checks in testedCells to see if it has alreadybeen tested; if so, it does not test it again. This optimization improvedthe speed of LifeTime by over 30 % (57 s down to 34 s). However, theextra memory required is significant: if there are 200 live cells in a generation, there will be some 800 tested cells.

At 23 bytes per cell, that isabout 18 KB.7.14.3 Tools for Optimization: a DiversionTaking a guess and test approach to improving performance or reducingmemory requirements can work, but is likely to be slow and tedious. Weneed tools and techniques to help us quickly and accurately identify thebottlenecks.We shall discuss two tools in this section: profiling and heap analysis.Arguably, the ability to carry out on-target profiling or heap analysisLIFETIME CASE STUDY373is more important to most wireless application developers than ontarget debugging.The Sun Wireless Toolkit emulator includes a basic profiler and aheap analysis tool. Why these are built into the emulator and not partof the IDE is a mystery.

It means we can only profile MIDlets runningunder the WTK emulator, not under a Symbian OS or any other generalemulator, and certainly not on a real device. Perhaps in the not too distantfuture we can look forward to an extension of the Universal EmulatorInterface (UEI). This is currently used to control debug sessions from anIDE in a standardized way, but could be enhanced to cover profiling andheap analysis.7.14.3.1 ProfilingProfiling tools allow us to see how much time is spent in a method andin a line of code in a method, to understand the calling tree, and to seehow much time a called method spent servicing calling methods.The Wireless Toolkit gathers profiling information during a run withno great impact on performance. The results are displayed when theemulator exits.

The display is split into two halves:• on the right is a list of all methods and the statistics for each method:the number of times the method was called, the total number ofcycles and the percentage of time spent in the method, and thenumber of cycles and the percentage excluding time spent in childmethods• on the left is the calling tree, which we can use to drill down andsee how much time each method spent executing on behalf of themethod that called it.Figures 7.8, 7.9 and 7.10 show the results from profiling LifeTime on asingle run.

All three show the same data, rearranged to bring out differentaspects. In Figure 7.8, the display has been arranged to show the methodsin order of the total execution time. We can immediately see that mostof our time was spent in LifeEngine.run().

The bulk of this, 73 %overall, was spent in LifeEngine.createNewCell(). This methodrepresents the bulk of the Game of Life algorithm. The fact that thismethod was also called more than 136 000 times suggests that there isroom for improvement.The rendering is handled by LifeCanvas.paintCanvas1(). Thisaccounts for only 13 % of the total execution time, so the benefits ofoptimization here are limited (as we discovered earlier).We get a different picture if we order methods by the time spent in themethod, excluding calls to child methods. Figure 7.9 shows that the most374WRITING OPTIMIZED CODEFigure 7.8Profiling LifeTime by total execution time of the methods.Figure 7.9Profiling LifeTime by time spent in the methods.expensive method is java.util.Hashtable.containsKey().

Themethod itself is fairly quick (unfortunately the profiler does not show theaverage time spent in each method invocation); however, we called itnearly 600 000 times because we are constantly checking to see if a cellis alive or empty.As we saw in Figure 7.8, some 13 % of the time was spent in LifeCanvas.paintCanvas(). However, from the calling graph in Figure 7.10,LIFETIME CASE STUDY375Figure 7.10 Profiling LifeTime by calling tree.we can see that most of that time was spent in nextElement() fromthe Hashtable Enumerator.53 % of the time was spent in HashGM.getNeighbourCount().The main culprits are Hashtable.containsKey() and the Cellconstructor.7.14.3.2 Heap AnalysisHeap analysis is the other side of profiling. Profiling is used to identifyperformance issues; heap analysis to identify memory issues.

Sun’s Wireless Toolkit heap analyzer displays running data, though with a seriousimpact on performance, by a factor of about 50.The tool provides two displays. The first is a graph of overall memoryusage (see Figure 7.11). This shows memory gradually increasing, thendropping as the garbage collector kicks in. Remember that this is the KVMgarbage collector. It would be quite fascinating to see a similar graph forCLDC HI behavior.The graph view reports that at the point the emulator was shut down,which was soon after the garbage collector ran, there were 1790 objects,occupying around 52 KB of heap.376WRITING OPTIMIZED CODEFigure 7.11 Graph of LifeTime memory usage.The objects view (see Figure 7.12) provides a more detailed breakdown of the heap utilization. Top of the list are the Cell objects: justover 1500, at 23 bytes each.

Характеристики

Тип файла
PDF-файл
Размер
5,73 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Зачем заказывать выполнение своего задания, если оно уже было выполнено много много раз? Его можно просто купить или даже скачать бесплатно на СтудИзбе. Найдите нужный учебный материал у нас!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6310
Авторов
на СтудИзбе
312
Средний доход
с одного платного файла
Обучение Подробнее