SlideShare una empresa de Scribd logo
1 de 28
PERFORMANCE AND
BENCHMARKING
David Wengier
@ch00k
premature optimization is
the root of all evil
premature optimization is
the root of all evil
- Donald Knuth
We should forget about small efficiencies,
say about 97% of the time: premature optimization is
the root of all evil. Yet we should not pass up our
opportunities in that critical 3%”
- Donald Knuth
“Programmers waste enormous amounts of time
thinking about, or worrying about, the speed of
noncritical parts of their programs, and these
attempts at efficiency actually have a strong negative
impact when debugging and maintenance are
considered. We should forget about small efficiencies,
say about 97% of the time: premature optimization is
the root of all evil. Yet we should not pass up our
opportunities in that critical 3%”
- Donald Knuth
“Programmers waste enormous amounts of time
thinking about, or worrying about, the speed of
noncritical parts of their programs, and these
attempts at efficiency actually have a strong negative
impact when debugging and maintenance are
considered. We should forget about small efficiencies,
say about 97% of the time: premature optimization is
the root of all evil. Yet we should not pass up our
opportunities in that critical 3%”
- Donald Knuth
“Structured Programming with Go To Statements”,
WHEN TO OPTIMIZE?
• Optimization is fine when we know we need to
• Look at the algorithm before the code
• Micro-benchmarking is fine if the code is on the hot path
• When experience tells you some things are objectively better
• When the better performing code has other benefits
HOW TO OPTIMIZE?
• Know the context
• Question assumptions
• Release builds only
• Measure
• Measure
• Measure
HOW TO OPTIMIZE?
public static void Profile(Action func)
{
DateTime start = DateTime.Now;
for (int i = 0; i < 100000; i++)
{
func();
}
Console.WriteLine("Time Elapsed {0} ms", (DateTime.Now - start).TotalMilliseconds);
}
HOW TO OPTIMIZE?
public static void Profile(Action func)
{
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
Thread.CurrentThread.Priority = ThreadPriority.Highest;
func();
Stopwatch watch = new Stopwatch();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
watch.Start();
for (int i = 0; i < 100000; i++)
{
func();
}
watch.Stop();
Console.WriteLine("Time Elapsed {0} ms", watch.Elapsed.TotalMilliseconds);
}
BENCHMARKDOTNET
(not Benchmark.Net)
public class Program
{
public static void Main(string[] args)
{
BenchmarkRunner.Run<Program>();
}
private string input = "1000";
[Benchmark]
public int IntParse()
{
return int.Parse(input);
}
[Benchmark]
public int ConvertToInt32()
{
return Convert.ToInt32(input);
}
}
HOW IT WORKS
• Separate process, separate run for each diagnostic.
• Pilot: The best operation count will be chosen.
• IdleWarmup, IdleTarget: Overhead will be evaluated.
• MainWarmup: Warmup of the main method.
• MainTarget: Main measurements.
• Result = MainTarget – AverageOverhead
http://benchmarkdotnet.org/HowItWorks.htm
LETS MICRO BENCHMARK!
• NO!
• Its too slow.
STRING.JOIN VS LINQ VS STRINGBUILDER VS
CONCATENATION
STRING.JOIN VS LINQ VS STRINGBUILDER VS
CONCATENATION
STRING.JOIN VS LINQ VS STRINGBUILDER VS
CONCATENATION
STRING.JOIN VS LINQ VS STRINGBUILDER VS
CONCATENATION
STRING.JOIN VS LINQ VS STRINGBUILDER VS
CONCATENATION
STRING.JOIN VS LINQ VS STRINGBUILDER VS
CONCATENATION
STRING.JOIN VS LINQ VS STRINGBUILDER VS
CONCATENATION
• Combining 3 x 20 character strings:
• StringBuilder: 126ns, 236 b
• Concatnation: 267ns, 213 b
• Combining 3 x 2,000,000 character strings:
• StringBuilder: 122.3 ms, 220 mb
• Concatenation: 230.9 ms, 343 mb
DICTIONARY<> VS IDICTIONARY<>
DICTIONARY<> VS IDICTIONARY<>
0 bytes allocated 32 bytes allocated
LOOPS VS LINQ
LOOPS VS LINQ
0 bytes 20 bytes 32 bytes
EXCEPTIONS VS NOT EXCEPTIONS
EXCEPTIONS VS NOT EXCEPTIONS
408 bytes 0 bytes
HYBRIDDICTIONARY
public class HybridDictionary: IDictionary {
// These numbers have been carefully tested to be optimal.
// Please don't change them without doing thorough performance
// testing.
private const int CutoverPoint = 9;
• Should you always use Dictionary<K,V> instead of IDictionary<K,V>? No, it
depends.
• Should you always use structs instead of classes? No, it depends.
• Should you always use for instead of foreach? No, it depends.
• Should you always use StringBuilder instead of concatenation? No, it depends.
• Should you always use traditional loops instead of Linq? No, it depends.
• Should you always avoid throwing exceptions? No, it depends.
• Should you always specify initial capacity on Lists and StringBuilders? Yes. Be nice.
SUMMARY

Más contenido relacionado

Similar a Performance and Benchmarking

Ups and downs of contract testing in real life
Ups and downs of contract testing in real lifeUps and downs of contract testing in real life
Ups and downs of contract testing in real lifeOleksandr Romanov
 
How I Learned to Stop Worrying and Love Legacy Code
How I Learned to Stop Worrying and Love Legacy CodeHow I Learned to Stop Worrying and Love Legacy Code
How I Learned to Stop Worrying and Love Legacy CodeGene Gotimer
 
Dev buchan 30 proven tips
Dev buchan 30 proven tipsDev buchan 30 proven tips
Dev buchan 30 proven tipsBill Buchan
 
Performance Tuning and Optimization
Performance Tuning and OptimizationPerformance Tuning and Optimization
Performance Tuning and OptimizationMongoDB
 
It Does What You Say, Not What You Mean: Lessons From A Decade of Program Repair
It Does What You Say, Not What You Mean: Lessons From A Decade of Program RepairIt Does What You Say, Not What You Mean: Lessons From A Decade of Program Repair
It Does What You Say, Not What You Mean: Lessons From A Decade of Program RepairClaire Le Goues
 
MongoDB at Baidu
MongoDB at BaiduMongoDB at Baidu
MongoDB at BaiduMat Keep
 
DockerCon SF 2019 - Observability Workshop
DockerCon SF 2019 - Observability WorkshopDockerCon SF 2019 - Observability Workshop
DockerCon SF 2019 - Observability WorkshopKevin Crawley
 
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query Pitfalls
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query PitfallsMongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query Pitfalls
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query PitfallsMongoDB
 
Lessons from running AppSync in prod
Lessons from running AppSync in prodLessons from running AppSync in prod
Lessons from running AppSync in prodYan Cui
 
Keynote AST 2016
Keynote AST 2016Keynote AST 2016
Keynote AST 2016Kim Herzig
 
DevOps: Find Solutions, Not More Defects
DevOps: Find Solutions, Not More DefectsDevOps: Find Solutions, Not More Defects
DevOps: Find Solutions, Not More DefectsTechWell
 
Low latency microservices in java QCon New York 2016
Low latency microservices in java   QCon New York 2016Low latency microservices in java   QCon New York 2016
Low latency microservices in java QCon New York 2016Peter Lawrey
 
Using SigOpt to Tune Deep Learning Models with Nervana Cloud
Using SigOpt to Tune Deep Learning Models with Nervana CloudUsing SigOpt to Tune Deep Learning Models with Nervana Cloud
Using SigOpt to Tune Deep Learning Models with Nervana CloudSigOpt
 
JavaOne 2016: Code Generation with JavaCompiler for Fun, Speed and Business P...
JavaOne 2016: Code Generation with JavaCompiler for Fun, Speed and Business P...JavaOne 2016: Code Generation with JavaCompiler for Fun, Speed and Business P...
JavaOne 2016: Code Generation with JavaCompiler for Fun, Speed and Business P...Juan Cruz Nores
 
Cassandra Tools and Distributed Administration (Jeffrey Berger, Knewton) | C*...
Cassandra Tools and Distributed Administration (Jeffrey Berger, Knewton) | C*...Cassandra Tools and Distributed Administration (Jeffrey Berger, Knewton) | C*...
Cassandra Tools and Distributed Administration (Jeffrey Berger, Knewton) | C*...DataStax
 
Things YouShould Be Doing When Using Cassandra Drivers
Things YouShould Be Doing When Using Cassandra DriversThings YouShould Be Doing When Using Cassandra Drivers
Things YouShould Be Doing When Using Cassandra DriversRebecca Mills
 
Sista: Improving Cog’s JIT performance
Sista: Improving Cog’s JIT performanceSista: Improving Cog’s JIT performance
Sista: Improving Cog’s JIT performanceESUG
 
SAST, fight against potential vulnerabilities
SAST, fight against potential vulnerabilitiesSAST, fight against potential vulnerabilities
SAST, fight against potential vulnerabilitiesAndrey Karpov
 
Go Reactive: Building Responsive, Resilient, Elastic & Message-Driven Systems
Go Reactive: Building Responsive, Resilient, Elastic & Message-Driven SystemsGo Reactive: Building Responsive, Resilient, Elastic & Message-Driven Systems
Go Reactive: Building Responsive, Resilient, Elastic & Message-Driven SystemsJonas Bonér
 
Growing Software and Growing Ourselves
Growing Software and Growing OurselvesGrowing Software and Growing Ourselves
Growing Software and Growing OurselvesDaniel Parkin
 

Similar a Performance and Benchmarking (20)

Ups and downs of contract testing in real life
Ups and downs of contract testing in real lifeUps and downs of contract testing in real life
Ups and downs of contract testing in real life
 
How I Learned to Stop Worrying and Love Legacy Code
How I Learned to Stop Worrying and Love Legacy CodeHow I Learned to Stop Worrying and Love Legacy Code
How I Learned to Stop Worrying and Love Legacy Code
 
Dev buchan 30 proven tips
Dev buchan 30 proven tipsDev buchan 30 proven tips
Dev buchan 30 proven tips
 
Performance Tuning and Optimization
Performance Tuning and OptimizationPerformance Tuning and Optimization
Performance Tuning and Optimization
 
It Does What You Say, Not What You Mean: Lessons From A Decade of Program Repair
It Does What You Say, Not What You Mean: Lessons From A Decade of Program RepairIt Does What You Say, Not What You Mean: Lessons From A Decade of Program Repair
It Does What You Say, Not What You Mean: Lessons From A Decade of Program Repair
 
MongoDB at Baidu
MongoDB at BaiduMongoDB at Baidu
MongoDB at Baidu
 
DockerCon SF 2019 - Observability Workshop
DockerCon SF 2019 - Observability WorkshopDockerCon SF 2019 - Observability Workshop
DockerCon SF 2019 - Observability Workshop
 
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query Pitfalls
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query PitfallsMongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query Pitfalls
MongoDB.local DC 2018: Tips and Tricks for Avoiding Common Query Pitfalls
 
Lessons from running AppSync in prod
Lessons from running AppSync in prodLessons from running AppSync in prod
Lessons from running AppSync in prod
 
Keynote AST 2016
Keynote AST 2016Keynote AST 2016
Keynote AST 2016
 
DevOps: Find Solutions, Not More Defects
DevOps: Find Solutions, Not More DefectsDevOps: Find Solutions, Not More Defects
DevOps: Find Solutions, Not More Defects
 
Low latency microservices in java QCon New York 2016
Low latency microservices in java   QCon New York 2016Low latency microservices in java   QCon New York 2016
Low latency microservices in java QCon New York 2016
 
Using SigOpt to Tune Deep Learning Models with Nervana Cloud
Using SigOpt to Tune Deep Learning Models with Nervana CloudUsing SigOpt to Tune Deep Learning Models with Nervana Cloud
Using SigOpt to Tune Deep Learning Models with Nervana Cloud
 
JavaOne 2016: Code Generation with JavaCompiler for Fun, Speed and Business P...
JavaOne 2016: Code Generation with JavaCompiler for Fun, Speed and Business P...JavaOne 2016: Code Generation with JavaCompiler for Fun, Speed and Business P...
JavaOne 2016: Code Generation with JavaCompiler for Fun, Speed and Business P...
 
Cassandra Tools and Distributed Administration (Jeffrey Berger, Knewton) | C*...
Cassandra Tools and Distributed Administration (Jeffrey Berger, Knewton) | C*...Cassandra Tools and Distributed Administration (Jeffrey Berger, Knewton) | C*...
Cassandra Tools and Distributed Administration (Jeffrey Berger, Knewton) | C*...
 
Things YouShould Be Doing When Using Cassandra Drivers
Things YouShould Be Doing When Using Cassandra DriversThings YouShould Be Doing When Using Cassandra Drivers
Things YouShould Be Doing When Using Cassandra Drivers
 
Sista: Improving Cog’s JIT performance
Sista: Improving Cog’s JIT performanceSista: Improving Cog’s JIT performance
Sista: Improving Cog’s JIT performance
 
SAST, fight against potential vulnerabilities
SAST, fight against potential vulnerabilitiesSAST, fight against potential vulnerabilities
SAST, fight against potential vulnerabilities
 
Go Reactive: Building Responsive, Resilient, Elastic & Message-Driven Systems
Go Reactive: Building Responsive, Resilient, Elastic & Message-Driven SystemsGo Reactive: Building Responsive, Resilient, Elastic & Message-Driven Systems
Go Reactive: Building Responsive, Resilient, Elastic & Message-Driven Systems
 
Growing Software and Growing Ourselves
Growing Software and Growing OurselvesGrowing Software and Growing Ourselves
Growing Software and Growing Ourselves
 

Más de David Wengier

A (very) opinionated guide to MSBuild and Project Files
A (very) opinionated guide to MSBuild and Project FilesA (very) opinionated guide to MSBuild and Project Files
A (very) opinionated guide to MSBuild and Project FilesDavid Wengier
 
Lowering in C#: What really happens with your code?, from NDC Oslo 2019
Lowering in C#: What really happens with your code?, from NDC Oslo 2019Lowering in C#: What really happens with your code?, from NDC Oslo 2019
Lowering in C#: What really happens with your code?, from NDC Oslo 2019David Wengier
 
Pragmatic Performance from NDC Oslo 2019
Pragmatic Performance from NDC Oslo 2019Pragmatic Performance from NDC Oslo 2019
Pragmatic Performance from NDC Oslo 2019David Wengier
 
Pragmatic Performance from NDC London 2019
Pragmatic Performance from NDC London 2019Pragmatic Performance from NDC London 2019
Pragmatic Performance from NDC London 2019David Wengier
 
A (brief) overview of Span<T>
A (brief) overview of Span<T>A (brief) overview of Span<T>
A (brief) overview of Span<T>David Wengier
 
Introduction to Amazon Echo Skills
Introduction to Amazon Echo SkillsIntroduction to Amazon Echo Skills
Introduction to Amazon Echo SkillsDavid Wengier
 

Más de David Wengier (6)

A (very) opinionated guide to MSBuild and Project Files
A (very) opinionated guide to MSBuild and Project FilesA (very) opinionated guide to MSBuild and Project Files
A (very) opinionated guide to MSBuild and Project Files
 
Lowering in C#: What really happens with your code?, from NDC Oslo 2019
Lowering in C#: What really happens with your code?, from NDC Oslo 2019Lowering in C#: What really happens with your code?, from NDC Oslo 2019
Lowering in C#: What really happens with your code?, from NDC Oslo 2019
 
Pragmatic Performance from NDC Oslo 2019
Pragmatic Performance from NDC Oslo 2019Pragmatic Performance from NDC Oslo 2019
Pragmatic Performance from NDC Oslo 2019
 
Pragmatic Performance from NDC London 2019
Pragmatic Performance from NDC London 2019Pragmatic Performance from NDC London 2019
Pragmatic Performance from NDC London 2019
 
A (brief) overview of Span<T>
A (brief) overview of Span<T>A (brief) overview of Span<T>
A (brief) overview of Span<T>
 
Introduction to Amazon Echo Skills
Introduction to Amazon Echo SkillsIntroduction to Amazon Echo Skills
Introduction to Amazon Echo Skills
 

Último

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 

Último (20)

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 

Performance and Benchmarking

  • 2. premature optimization is the root of all evil
  • 3. premature optimization is the root of all evil - Donald Knuth
  • 4. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%” - Donald Knuth
  • 5. “Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%” - Donald Knuth
  • 6. “Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%” - Donald Knuth “Structured Programming with Go To Statements”,
  • 7. WHEN TO OPTIMIZE? • Optimization is fine when we know we need to • Look at the algorithm before the code • Micro-benchmarking is fine if the code is on the hot path • When experience tells you some things are objectively better • When the better performing code has other benefits
  • 8. HOW TO OPTIMIZE? • Know the context • Question assumptions • Release builds only • Measure • Measure • Measure
  • 9. HOW TO OPTIMIZE? public static void Profile(Action func) { DateTime start = DateTime.Now; for (int i = 0; i < 100000; i++) { func(); } Console.WriteLine("Time Elapsed {0} ms", (DateTime.Now - start).TotalMilliseconds); }
  • 10. HOW TO OPTIMIZE? public static void Profile(Action func) { Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High; Thread.CurrentThread.Priority = ThreadPriority.Highest; func(); Stopwatch watch = new Stopwatch(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); watch.Start(); for (int i = 0; i < 100000; i++) { func(); } watch.Stop(); Console.WriteLine("Time Elapsed {0} ms", watch.Elapsed.TotalMilliseconds); }
  • 11. BENCHMARKDOTNET (not Benchmark.Net) public class Program { public static void Main(string[] args) { BenchmarkRunner.Run<Program>(); } private string input = "1000"; [Benchmark] public int IntParse() { return int.Parse(input); } [Benchmark] public int ConvertToInt32() { return Convert.ToInt32(input); } }
  • 12. HOW IT WORKS • Separate process, separate run for each diagnostic. • Pilot: The best operation count will be chosen. • IdleWarmup, IdleTarget: Overhead will be evaluated. • MainWarmup: Warmup of the main method. • MainTarget: Main measurements. • Result = MainTarget – AverageOverhead http://benchmarkdotnet.org/HowItWorks.htm
  • 13. LETS MICRO BENCHMARK! • NO! • Its too slow.
  • 14. STRING.JOIN VS LINQ VS STRINGBUILDER VS CONCATENATION
  • 15. STRING.JOIN VS LINQ VS STRINGBUILDER VS CONCATENATION
  • 16. STRING.JOIN VS LINQ VS STRINGBUILDER VS CONCATENATION
  • 17. STRING.JOIN VS LINQ VS STRINGBUILDER VS CONCATENATION
  • 18. STRING.JOIN VS LINQ VS STRINGBUILDER VS CONCATENATION
  • 19. STRING.JOIN VS LINQ VS STRINGBUILDER VS CONCATENATION
  • 20. STRING.JOIN VS LINQ VS STRINGBUILDER VS CONCATENATION • Combining 3 x 20 character strings: • StringBuilder: 126ns, 236 b • Concatnation: 267ns, 213 b • Combining 3 x 2,000,000 character strings: • StringBuilder: 122.3 ms, 220 mb • Concatenation: 230.9 ms, 343 mb
  • 22. DICTIONARY<> VS IDICTIONARY<> 0 bytes allocated 32 bytes allocated
  • 24. LOOPS VS LINQ 0 bytes 20 bytes 32 bytes
  • 25. EXCEPTIONS VS NOT EXCEPTIONS
  • 26. EXCEPTIONS VS NOT EXCEPTIONS 408 bytes 0 bytes
  • 27. HYBRIDDICTIONARY public class HybridDictionary: IDictionary { // These numbers have been carefully tested to be optimal. // Please don't change them without doing thorough performance // testing. private const int CutoverPoint = 9;
  • 28. • Should you always use Dictionary<K,V> instead of IDictionary<K,V>? No, it depends. • Should you always use structs instead of classes? No, it depends. • Should you always use for instead of foreach? No, it depends. • Should you always use StringBuilder instead of concatenation? No, it depends. • Should you always use traditional loops instead of Linq? No, it depends. • Should you always avoid throwing exceptions? No, it depends. • Should you always specify initial capacity on Lists and StringBuilders? Yes. Be nice. SUMMARY

Notas del editor

  1. Heard this? Who said it?
  2. Donald Knuth. You may notice the formatting is odd.. Well, that’s because its part of a bigger quote
  3. Most people don’t know this. 97% of the time its evil, the rest its not. But why? Notice the quotes.
  4. Consider maintenance and debugging. Readability. Etc. Bonus points, what paper was it from?
  5. Ironically, a quote that lots of developers spout as being gospel comes from a paper arguing that programming with go to statements is perfectly fine. A debate for another time.
  6. So when do we optimize? When we should. Split the string? What about streams? StringSegments? Don’t focus on the loop Measure the hot path Pragmatism says draw on your experience Other benefits, like reusability or readability.
  7. To avoid a micro-benchmark, know the context of your data. How much? How often? Questions assumptions: “the compiler will fix this”. Will it? Release builds only! Measure
  8. DateTime is as precise as stopwatch, but not as granular Doesn’t account for JITing
  9. High affinity, so nothing else on the machine matters (hopefully) JIT first Get GC out of the way, because GC pauses are bad for benchmarking Then go
  10. Or use BenchmarkDotNet
  11. So I’ve told you how to benchmark, and that you should basically never do it, so lets do it.
  12. Except its too slow. BenchmarkDotNet is too awesome for live demos. I have some canned ones.
  13. Concat wins Then stringbuilder StringBuilder again Now StringBuilder with capacity, and that trend continues forever If we add more, we can see stringbuilder and string join are both a lot fast As we keep going, the difference gets bigger Looks like a slam dunk right? Always use a string builder with capacity? BUT- don’t forget context!!! Look what happens as the strings get longer. Now it doesn’t matter so much, as long as you don’t concatenate
  14. Concat wins Then stringbuilder StringBuilder again Now StringBuilder with capacity, and that trend continues forever If we add more, we can see stringbuilder and string join are both a lot fast As we keep going, the difference gets bigger Looks like a slam dunk right? Always use a string builder with capacity? BUT- don’t forget context!!! Look what happens as the strings get longer. Now it doesn’t matter so much, as long as you don’t concatenate
  15. Concat wins Then stringbuilder StringBuilder again Now StringBuilder with capacity, and that trend continues forever If we add more, we can see stringbuilder and string join are both a lot fast As we keep going, the difference gets bigger Looks like a slam dunk right? Always use a string builder with capacity? BUT- don’t forget context!!! Look what happens as the strings get longer. Now it doesn’t matter so much, as long as you don’t concatenate
  16. Concat wins Then stringbuilder StringBuilder again Now StringBuilder with capacity, and that trend continues forever If we add more, we can see stringbuilder and string join are both a lot fast As we keep going, the difference gets bigger Looks like a slam dunk right? Always use a string builder with capacity? BUT- don’t forget context!!! Look what happens as the strings get longer. Now it doesn’t matter so much, as long as you don’t concatenate
  17. Back to context, again production code.. For 3 small strings, concatenation is slower, but not measurably so. But it uses less memory. The overhead of StringBuilder might make it a winner. For large strings, not so. Stopwatch granularity is around 300ns, so the difference in the first one is effectively unmeasurable in production .NET code.
  18. The overhead of a class vs struct, virtual calls, etc. makes the difference. So if you use Idictionary as your parameters are you’re supposed to do, on a hot path that might be a negative. Question assumptions.. How many of you think “coding to interfaces” is _always_ better?
  19. I’m an old man so I like loops, but Linq has an overhead.
  20. Overhead in method invocations and allocations. Even the Where vs FirstOrDefault examples, because there are more iterators being allocated.
  21. 50% chance of having an invalid number. The important thing is that both benchmarks will use exactly the same input.
  22. We all know exceptions are slow, but they’re really slow. They have to collect debug information, context, stack trace etc. Don’t use for control flow.
  23. Measure! Take a leaf out of microsofts book. Know your input data. Know your context. Use the correct type.