Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Alex Barney
- 01-11-2019
- Programs Written On Programming Stream 2019 #1
- _____________________________________________________________________________________
- 1) META.CPP
- // Program: meta.cpp
- // Description: sample program to illustrate the differnce in RunTime
- // and CompileTime function implementations.
- #include <stdio.h>
- #include <stdint.h>
- #include <time.h>
- using namespace std;
- // RunTime version
- uint32_t sig(uint32_t n)
- {
- return n == 0 ? n : n + sig(n-1);
- }
- // CompileTime version
- template<uint32_t n> struct sigma
- {
- enum
- {
- sum = sigma<n-1>::sum + n
- };
- };
- template<> struct sigma<1>{enum{sum = 1};};
- int main()
- {
- clock_t t = clock();
- printf("CompTime:%d\nTime: %.6fs\n", sigma<5>::sum,
- (double)(clock() - t)/CLOCKS_PER_SEC);
- printf("RunTime:%d\nTime: %.6fs\n", sig(5),
- (double)(clock() - t)/CLOCKS_PER_SEC);
- }
- SAMPLE OUTPUT:
- $ ./meta
- CompTime:15
- Time: 0.000007s
- RunTime:15
- Time: 0.000427s
- _____________________________________________________________________________________
- 2) CAST.CPP
- // Program: cast.cpp
- // Description: sample program to illustrate the differnce in RunTime
- // and CompileTime casting implementations.
- #include <stdio.h>
- #include <stdint.h>
- #include <time.h>
- using namespace std;
- uint16_t rt(char a)
- {
- int b = (int)(a);
- float c = (float) (a/10);
- uint16_t d = (uint16_t) (a*1000);
- return d;
- }
- uint16_t ct(char a)
- {
- int b = static_cast<int>(a);
- float c = static_cast<float>(a/10);
- uint16_t d = static_cast<uint16_t>(a*1000);
- return d;
- }
- int main()
- {
- clock_t t = clock();
- printf("ct: %d\nt: %.6fs\n", ct('m'),
- (double)(clock() - t)/CLOCKS_PER_SEC);
- printf("rt: %d\nt: %.6fs\n", rt('m'),
- (double)(clock() - t)/CLOCKS_PER_SEC);
- }
- SAMPLE OUTPUT:
- $ ./cast
- ct: 43464
- t: 0.000004s
- rt: 43464
- t: 0.000232s
Add Comment
Please, Sign In to add comment