c - 快速替换数组中元素的方法 - C

标签 c arrays performance

假设我们有一个像这样的整数数组:

const int size = 100000;
int array[size];
//set some items to 0 and other items to 1

我想用另一个值替换所有值为 1 的项目,例如 123456。 这可以通过以下方式轻松实现:

for(int i = 0; i < size ; i++){
    if(array[i] != 0) 
        array[i] = 123456;
}

出于好奇,是否有更快的方法来执行此操作,通过某种 x86 技巧,或者这是处理器的最佳代码?

最佳答案

对于您最初有 0 和 1 的特定情况,以下可能更快。你必须对它进行基准测试。但是,您可能无法使用纯 C 做得更好;如果您想利用可能存在的“x86 技巧”,您可能需要深入研究汇编。

for(int i = 0; i < size ; i++){
  array[i] *= 123456;
}

编辑:

基准代码:

#include <time.h>
#include <stdlib.h>
#include <stdio.h>

size_t diff(struct timespec *start, struct timespec *end)
{
  return (end->tv_sec - start->tv_sec)*1000000000 + end->tv_nsec - start->tv_nsec;
}

int main(void)
{
  const size_t size = 1000000;
  int array[size];

  for(size_t i=0; i<size; ++i) {
    array[i] = rand() & 1;
  }

  struct timespec start, stop;

  clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start);
  for(size_t i=0; i<size; ++i) {
    array[i] *= 123456;
    //if(array[i]) array[i] = 123456;
  }
  clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &stop);

  printf("size: %zu\t nsec: %09zu\n", size, diff(&start, &stop));
}

我的结果:

计算机:四核 AMD Phenom @2.5GHz,Linux,GCC 4.7,编译

$ gcc arr.c -std=gnu99 -lrt -O3 -march=native
  • if 版本:~5-10ms
  • *= 版本:~1.3ms

关于c - 快速替换数组中元素的方法 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16231110/

相关文章:

c - 在 C 中使用 "realloc"的问题

performance - 字符串连接的性能比较

mysql 索引以获得更好的选择性能

c - 在 C 中使用结构或多维数组

c - printf 导致输出问题

arrays - 如何识别 MATLAB 中数据存储在数组边界之外的位置?

javascript - JSON Stringify 正在将对象数组的值设置为空的对象键

javascript - 跨网站缓存Javascript库

c - 如何在cmd中使c语言的文本着色?

javascript - 在JS数组中存储单个大索引是错误的吗?