Advertisement
sci4me

strcpy vs strcpy_s

Jan 24th, 2020
322
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.39 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <intrin.h>
  5.  
  6. #pragma intrinsic(__rdtsc)
  7.  
  8. typedef unsigned char u8;
  9. typedef unsigned long long u64;
  10.  
  11. int main() {
  12.     constexpr u64 W = 128; // warmup iterations
  13.     constexpr u64 M = 1024; // test iterations
  14.     constexpr u64 N = 1024 * 64; // bytes to copy per string
  15.  
  16.     char* input = (char*)malloc(N);
  17.     char* output = (char*)malloc(N);
  18.  
  19.     if (input == 0|| output == 0) {
  20.         fprintf(stderr, "Failed to allocate testing memory\n");
  21.         return 1;
  22.     }
  23.  
  24.     // build string to be copied
  25.     for (u64 i = 0; i < N - 1; i++) {
  26.         u8 x = 0;
  27.         do {
  28.             x = (u8)(rand() & 0xFF);
  29.         } while (x == 0);
  30.        
  31.         input[i] = x;
  32.     }
  33.     input[N - 1] = 0;
  34.  
  35.     // strcpy warmup
  36.     for (u64 i = 0; i < W; i++) {
  37.         strcpy(output, input);
  38.     }
  39.  
  40.     // strcpy perf test
  41.     u64 strcpy_total = 0;
  42.     for (u64 i = 0; i < M; i++) {
  43.         u64 start = __rdtsc();
  44.         strcpy(output, input);
  45.         strcpy_total += __rdtsc() - start;
  46.     }
  47.  
  48.     // strcpy_s warmup
  49.     for (u64 i = 0; i < W; i++) {
  50.         strcpy_s(output, N, input);
  51.     }
  52.  
  53.     // strcpy_s perf test
  54.     u64 strcpy_s_total = 0;
  55.     for (u64 i = 0; i < M; i++) {
  56.         u64 start = __rdtsc();
  57.         strcpy_s(output, N, input);
  58.         strcpy_s_total += __rdtsc() - start;
  59.     }
  60.  
  61.     printf("strcpy:   %llu %lf\n", strcpy_total, (double)strcpy_total / (double)M);
  62.     printf("strcpy_s: %llu %lf\n", strcpy_s_total, (double)strcpy_s_total / (double)M);
  63.  
  64.     return 0;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement