electra13x7777

Programs Written On Programming Stream 2019 #1

Jan 11th, 2019
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.95 KB | None | 0 0
  1. Alex Barney
  2. 01-11-2019
  3. Programs Written On Programming Stream 2019 #1
  4.  
  5. _____________________________________________________________________________________
  6.  
  7. 1) META.CPP
  8.  
  9. // Program: meta.cpp
  10. // Description: sample program to illustrate the differnce in RunTime
  11. //              and CompileTime function implementations.
  12. #include <stdio.h>
  13. #include <stdint.h>
  14. #include <time.h>
  15.  
  16. using namespace std;
  17.  
  18. // RunTime version
  19. uint32_t sig(uint32_t n)
  20. {
  21.     return n == 0 ? n : n + sig(n-1);
  22. }
  23.  
  24. // CompileTime version
  25. template<uint32_t n> struct sigma
  26. {
  27.     enum
  28.     {
  29.         sum = sigma<n-1>::sum + n
  30.     };
  31. };
  32.  
  33. template<> struct sigma<1>{enum{sum = 1};};
  34.  
  35. int main()
  36. {
  37.     clock_t t = clock();
  38.     printf("CompTime:%d\nTime: %.6fs\n", sigma<5>::sum,
  39.             (double)(clock() - t)/CLOCKS_PER_SEC);
  40.     printf("RunTime:%d\nTime: %.6fs\n", sig(5),
  41.             (double)(clock() - t)/CLOCKS_PER_SEC);
  42. }
  43.  
  44. SAMPLE OUTPUT:
  45. $ ./meta
  46. CompTime:15
  47. Time: 0.000007s
  48. RunTime:15
  49. Time: 0.000427s
  50.  
  51. _____________________________________________________________________________________
  52.  
  53. 2) CAST.CPP
  54.  
  55. // Program: cast.cpp
  56. // Description: sample program to illustrate the differnce in RunTime
  57. //              and CompileTime casting implementations.
  58.  
  59. #include <stdio.h>
  60. #include <stdint.h>
  61. #include <time.h>
  62.  
  63. using namespace std;
  64.  
  65. uint16_t rt(char a)
  66. {
  67.     int b = (int)(a);
  68.     float c = (float) (a/10);
  69.     uint16_t d = (uint16_t) (a*1000);
  70.     return d;
  71. }
  72.  
  73. uint16_t ct(char a)
  74. {
  75.     int b = static_cast<int>(a);
  76.     float c = static_cast<float>(a/10);
  77.     uint16_t d = static_cast<uint16_t>(a*1000);
  78.     return d;
  79. }
  80.  
  81. int main()
  82. {
  83.     clock_t t = clock();
  84.  
  85.     printf("ct: %d\nt: %.6fs\n", ct('m'),  
  86.             (double)(clock() - t)/CLOCKS_PER_SEC);
  87.     printf("rt: %d\nt: %.6fs\n", rt('m'),
  88.             (double)(clock() - t)/CLOCKS_PER_SEC);
  89. }
  90.  
  91. SAMPLE OUTPUT:
  92. $ ./cast
  93. ct: 43464
  94. t: 0.000004s
  95. rt: 43464
  96. t: 0.000232s
Add Comment
Please, Sign In to add comment