Using MATLAB (779505), страница 34

Файл №779505 Using MATLAB (Using MATLAB) 34 страницаUsing MATLAB (779505) страница 342017-12-27СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

In this case it’s important to determine which of yourfunctions are responsible for such calls.The profiler often helps to uncover problems that you can solve by:• Avoiding unnecessary computation, which can arise from oversight.• Changing your algorithm to avoid costly functions.• Avoiding recomputation by storing results for future use.When you reach the point where most of the time is spent on calls to a smallnumber of built-in functions, you have probably optimized the code as much asyou can expect.8-38Improving M-File Performance – the ProfilerUsing the ProfilerUse the profile function to generate and view statistics.1 Start the profiler by typing profile on in the Command Window. Specifyany options you want to use.2 Execute your M-file.The profiler counts how many seconds each line in the M-files use.

Theprofiler works cumulatively, that is, adding to the count for each M-file youexecute until you clear the statistics.3 Use profile report to display the statistics gathered in anHTML-formatted report in your system’s default Web browser.The profile FunctionHere is a summary of the main forms of profile. For details about these andother options, type doc profile.SyntaxOptionStarts the profiler, clearing previously recordedstatistics.profile on-detail levelSpecifies the level of function to be profiled.-historySpecifies that the exact sequence of functioncalls is to be recorded.profile offSuspends the profiler.profile reportSuspends the profiler, generates a profile reportin HTML format, and displays the report inyour system’s default Web browser.basename8-4DescriptionSaves the report in the file basename in thecurrent directory.Using the ProfilerSyntaxOptionDescription (Continued)profile plotSuspends the profiler and displays in a figurewindow a bar graph of the functions using themost execution time.profile resumeRestarts the profiler without clearingpreviously recorded statistics.profile clearClears the statistics recorded by the profiler.s = profile('status')Displays a structure containing the currentprofiler status.stats = profile('info')Suspends the profiler and displays a structurecontaining profiler results.Some people use profile simply to see the child functions; see also depfun forthat purpose.8-58Improving M-File Performance – the ProfilerAn Example Using the ProfilerThis example demonstrates how to run the profiler.1 To start the profiler, type in the Command Windowprofile on -detail builtin -historyThe -detail builtin option instructs the profiler to gather statistics forbuilt-in functions, in addition to the default M-functions, M-subfunctions,and MEX-functions.The -history option instructs the profiler to track the exact sequence ofentry and exit calls.2 Execute an M-file.

This example runs the Lotka-Volterra predator-preypopulation model. For more information about this model, type lotkademoto run a demonstration.[t,y] = ode23('lotka',[0 2],[20;20]);3 Generate the profile report and save the results to the file lotkaprof.profile report lotkaprofThis suspends the profiler, displays the profile report in your system’sdefault Web browser, and saves the results.

See “Viewing Profiler Results”on page 8-7 for more information.4 Restart the profiler, without clearing the existing statistics.profile resumeThe profiler is now ready to continue gathering statistics for any moreM-files you run. It will add these new statistics to those generated in theprevious steps.5 Stop the profiler when you are finished gathering statistics.profile off8-6Viewing Profiler ResultsViewing Profiler ResultsThere are two main ways to view the profiler results:• “Viewing Profile Reports” on page 8-7• “Profile Plot” on page 8-12To save results, see “Saving Profile Reports” on page 8-13.Viewing Profile ReportsTo display profiler results, typeprofile reportThis suspends the profiler and produces three reports:• “Summary Profile Report” on page 8-7• “Function Details Profile Report” on page 8-10• “Function Call History Profile Report” on page 8-11The summary report appears in your system’s default Web browser.

Use thelinks at the top of the report page to see the other reports.Summary Profile ReportThe summary report presents statistics about the overall execution andprovides summary statistics for each function called. Values reported include:• Number of functions – The numbers of built-in functions, M-functions, andM-subfunctions are reported.• Clock precision – The precision of the profiler’s time measurement.

WhenTime for a function is 0, it is actually a positive value, but smaller than theprofiler can detect given the clock precision.• Time columns – The total time spent in a function, including all childfunctions called. Because the time for a function includes time spent on childfunctions, the times do not add up to the Total recorded time and thepercentages add up to more than 100%.• Self time columns – The total time spent in a function, not including time forany child functions called. Adding the Self time values for all functions listed8-78Improving M-File Performance – the Profilerequals the Total recorded time. The Self time percentages for all functionsadd up to approximately 100%.Note that the profiler itself uses some time, which is included in the profilerresults.Following is the summary report for the Lotka-Volterra model described in “AnExample Using the Profiler” on page 8-6.8-8Viewing Profiler ResultsView summary report (shownin this illustration).View details for allfunctions.View sequence offunction calls.Total time profiler wasrecording.Follow link to viewdetails for each function.Report includes built-infunctions because-detail builtinoption was used.Time per function includes timespent in child functions.Self time does NOT include timespent in child functions.8-98Improving M-File Performance – the ProfilerFunction Details Profile ReportThe function details report provides statistics for the parent and childfunctions of a function, and reports the line numbers on which the most timewas spent.

Following is detail report for the lotka function, which is one of thefunctions called in “An Example Using the Profiler” on page 8-6.Time in seconds8-10Percentage of thefunction’s timespent on that lineLine numberViewing Profiler ResultsFunction Call History Profile ReportThe function call history displays the exact sequence of functions called. Toview this report, you must have started the profiler using the -history option.profile on -historyThe profiler records up to 10,000 function entry and exit events. For more than10,000 events, the profiler continues to record other profile statistics, but notthe sequence of calls. Following is the history report generated from “AnExample Using the Profiler” on page 8-6.Exact sequenceof calls8-118Improving M-File Performance – the ProfilerProfile PlotTo view a bar graph for the functions using the most execution time, typeprofile plotThis suspends the profiler.

The bar graph appears in a figure window.Following is the bar graph generated from “An Example Using the Profiler” onpage 8-6.8-12Viewing Profiler ResultsSaving Profile ReportsWhen you generate the profile report, use the option to save it. For example,profile report basenamesaves the profile report to the file basename in the current directory. Later youcan view the saved results using a Web browser.Another way to save results is with the info = profile function, whichdisplays a structure containing the profiler results. Save this structure so thatlater you can generate and view the profile report using profreport(info).Example Using Structure of Profiler ResultsThe profiler results are stored in a structure that you can view or access.

Thisexample illustrates how you can view the results.1 Run the profiler for code that computes the Lotka-Volterra predator-preypopulation model.profile on -detail builtin -history[t,y] = ode23('lotka',[0 2],[20;20]);2 To view the structure containing profiler results, typestats = profile('info')MATLAB returnsstats =FunctionTable:FunctionHistory:ClockPrecision:Name:[41x1 struct][2x826 double]0.0100'MATLAB'3 You can view and access the contents of the structure.

For example, typestats.FunctionTable8-138Improving M-File Performance – the ProfilerMATLAB displays the FunctionTable structure.ans =41x1 struct array with fields:FunctionNameFileNameTypeNumCallsTotalTimeTotalRecursiveTimeChildrenParentsExecutedLines4 To view the contents of an element in the FunctionTable structure, type, forexample,stats.FunctionTable(2)MATLAB returns the second element in the structure.ans =FunctionName:FileName:Type:NumCalls:TotalTime:TotalRecursiveTime:Children:Parents:ExecutedLines:5 Save the results.save profstats8-14'horzcat''''Builtin-function'430.01000.0100[0x1 struct][2x1 struct][0x3 double]Viewing Profiler Results6 In a later session, to generate the profiler report using the saved results,typeload profstatsprofreport(stats)MATLAB displays the profile report.8-158Improving M-File Performance – the Profiler8-169Interfacing with SourceControl SystemsProcess of Interfacing to an SCS .

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

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

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

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